Dewang Dave
Dewang Dave

Reputation: 49

How to use IF ELSE in YAML with variable?

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.

Upvotes: 3

Views: 7389

Answers (1)

Gary521
Gary521

Reputation: 231

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.

Upvotes: 2

Related Questions