item as part of a variable

Moin,

I’m calling a playbook (ansible 2.4.2.0) with extra-vars for 3 system components, e.g. “foo_version=0.11.3 bar_version=0.10.2 baz_version=0.12.1 env=dev”.

There is a statement In the playbook that takes care that this step is only executed if the corresponding variable is defined: “{{ item }}_version”.

  • name: copy war file
    copy:
    src: “{{ tmpdir.path }}/{{ item }}.war”
    dest: /opt/tomcat/webapps/
    owner: tomcat
    group: root
    mode: 0440
    when:
  • “{{ item }}_version” is defined
    with_items:
  • foo
  • bar
  • baz

But this fail:

The offending line appears to be:

  • “{{ item }}_version” is defined
    ^ here
    We could be wrong, but this one looks like it might be an issue with
    missing quotes.

How can I check if the variable is set?

Thanks

That won't work, try:

  - name: copy war file
    copy:
      src: "{{ tmpdir.path }}/{{ item }}.war"
      dest: /opt/tomcat/webapps/
      owner: tomcat
      group: root
      mode: 0440
    when: item + "_version" in hostvars[inventory_hostname]
    with_items:
      - foo
      - bar
      - baz

You will need to construct a key, and reference the value through hostvars like:

when:

  • hostvars[inventory_hostname][item ~ “_version”] is defined