如何根据条件设置不同的参数

How to set different different arguments depending on when condition

我想使用 when 条件,以便根据主机使用不同的路径,剧本是有限的。我的剧本已经这样做了,但非常不清楚,因为我对清单的每个主机都有一个条目做同样的事情。

- 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"

为了清楚起见,我省略了其他条目。有什么方法可以做这样的事情吗?

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

所以基本上我只想要一个块或条目,它根据时间条件或受限主机设置目标字段。我已经看到可以通过设置 main.yml 并使用不同的 yml 来替代,如下所示:

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

通过这个解决方案,我没有在一个文件中有多个条目,而是有一个条目的多个文件。有谁知道是否可以在中间加一个?

如果我理解正确的话,当你可以使用“或”或“和”时,你想对同一事物进行更多的比较。 这个问题可能会导致一些误解,如果这不符合实际情况,请用您想要的确切结果更新问题。 :)

完整示例:

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

将数据放入字典中。例如,剧本

- 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 }}"

和库存

[switch1]
routerA
routerB

[switch2]
routerC

[switch3]
routerD

给出(删节)

    "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"