How to set different different arguments depending on when condition

212 Views Asked by At

I'd like to use a when condition so different paths are used depending on the host the playbook is limited. My playbook does this already but is very unclear as I have for every host of the inventory one entry doing the same.

- name: copy yaml
  copy:
    src: /home/host1
    dest: /home/ipcnet01/pipper
  when: "'switch1' in group_names"
- name: copy yaml
  copy:
    src: /home/root
    dest: /home/ipcnet02
  when: "'switch2' in group_names"

I have left out the other entries to keep it clearly here. Is there a way I can do something like this?

- name: copy yaml
  copy:
    src: /home/root
    dest: '/home/ipcnet01' |'/home/ipcnet01'
  when: "'switch1' in group_names |'switch2' in group_names"

So basically I just want one block or entry which sets the destination field dependent on the when condition or the limited host. I've seen that there is an alternative by setting the main.yml and using different ymls like here:

- include_tasks: copy_files_to_switch01.yml
  when: "'switch01' in group_names"
- include_tasks: copy_files_to_switch02.yml
  when: "'switch02' in group_names"

By this solution I don't have multiple entries in one file, but multiple files with a single entry. Does anyone know if it's possible to it with one as oin the middle?

2

There are 2 best solutions below

0
On BEST ANSWER

Put the data into a dictionary. For example, the playbook

- hosts: all
  vars:
    copy_dict:
      switch1:
        - {src: /home/host1, dest: /home/ipcnet01/pipper}
        - {src: /home/root, dest: /home/ipcnet01}
      switch2:
        - {src: /home/root, dest: /home/ipcnet02}
        - {src: /home/root, dest: /home/ipcnet01}
  tasks:
    - debug:
        msg: "{{inventory_hostname}}: copy {{ item.src }} to {{ item.dest }}"
      loop: "{{ group_names|intersect(copy_dict)|
                map('extract', copy_dict)|flatten }}"

and the inventory

[switch1]
routerA
routerB

[switch2]
routerC

[switch3]
routerD

give (abridged)

    "msg": "routerB: copy /home/host1 to /home/ipcnet01/pipper"
    "msg": "routerB: copy /home/root to /home/ipcnet01"
    "msg": "routerA: copy /home/host1 to /home/ipcnet01/pipper"
    "msg": "routerA: copy /home/root to /home/ipcnet01"
    "msg": "routerC: copy /home/root to /home/ipcnet02"
    "msg": "routerC: copy /home/root to /home/ipcnet01"
0
On

If I understand correctly you want to do more comprobations on the same when you can use "or" or "and". The question might lead a little bit to misunderstand, if that doesn't fit the case please update the question with the exact outcome you want. :)

Full example:

- name: copy yaml
  copy:
    src: /home/root
    dest: '/home/ipcnet01' |'/home/ipcnet01'
  when: '"switch01" in group_names' or '"switch2 in group_names'