3

I am using a YAML file for the Ansible Tower with the following information

- name: "Package Deployment"
  block:
    - name: "Update package {{ package }}"
      yum:
        update_cache: True
        update_only: True
        name: "{{ package }}{{ '' if (version is not defined or version == 'latest') else '-{{ version }}' }}"
        state: "{{ state|default('latest' if version == 'latest' else 'present') }}"
      become: true

When I passed the YAML variables

package: package
version: latest

then it prints package but if I pass YAML variables as

package: package
version: 22

then it prints package-{{ version }} instead of package-22.

U880D
  • 8,601
  • 6
  • 24
  • 40
Dewang Dave
  • 49
  • 2
  • 10
  • 3
    [moustache do not stack](https://stackoverflow.com/questions/46209556/how-can-i-use-ansible-nested-variable/46209588#46209588): `"{{ package }}{{ '' if (version is not defined or version == 'latest') else '-' ~ version }}"` – β.εηοιτ.βε Apr 28 '21 at 20:11

1 Answers1

2

Use string below to replace yours:

{{ '' if (version is not defined or version == 'latest') else '-' + version }}

Note that version has to be defined as string type, otherwise you need to add string cast.

U880D
  • 8,601
  • 6
  • 24
  • 40
Gary521
  • 201
  • 2
  • 7
  • 1
    You should [format your code](https://stackoverflow.com/editing-help), in your answers. Also, using `+` is dangerous, because it will only work if the two variables are strings, otherwise it might bring odd behavior, it would be better to advise to use the proper concatenation operator: `~`: [*Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the `~` operator.*](https://jinja.palletsprojects.com/en/2.11.x/templates/#math) – β.εηοιτ.βε Apr 29 '21 at 08:33