tom_nb_ny
tom_nb_ny

Reputation: 180

Ansible task variable fallback for with_items

I'm wondering if there's a way to instruct ansible to use the first variable found in a with_items parameter, for example:

- name: install additional php.d ini files
  template: src=etc/opt/remi/php82/{{ item }} dest=/etc/opt/remi/php82/{{ item }}
  with_items: "{{ Server.Php82.AdditionalInis | Group.Php82.AdditionalInis | [] }}"
  notify:
   - restart apache

In the above example:

  1. Use Server.Php82.AdditionalInis optionally defined in the host file, or;
  2. Use Group.Php82.AdditionalInis optionally defined in a shared group file, or:
  3. Skip the task, in that order.

Is something like this possible? I have seen {{ var | default('my_var') }} but it only supports a single fallback, as far as I could see. I also don't know how to skip the task when nothing is found.

Any help would be appreciated - Thanks

Upvotes: 0

Views: 186

Answers (1)

D3pRe5s
D3pRe5s

Reputation: 46

You can try to do two tasks with variable condition, like this:

- name: condition 1
  template: //smth//
  when: Server.Php82.AdditionalInis is defined

- name: condition 2
  template: //smth//
  when: (Group.Php82.AdditionalInis is defined and Server.Php82.AdditionalInis is not defined)

but chain-defaults in prev comment looks more smart :)

"{{ Server.Php82.AdditionalInis | default(Group.Php82.AdditionalInis) | default([]) }}"

Upvotes: 1

Related Questions