【问题标题】:How to set different different arguments depending on when condition如何根据条件设置不同的参数
【发布时间】:2020-12-01 15:12:40
【问题描述】:

我想使用 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"

所以基本上我只想要一个块或条目,它根据 when 条件或受限主机设置目标字段。我已经看到通过设置 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"

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

【问题讨论】:

    标签: ansible ansible-template


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果我理解正确,当您可以使用“或”或“和”时,您想对同一件事做更多的批评。 这个问题可能会导致一些误解,如果这不适合这种情况,请使用您想要的确切结果更新问题。 :)

      完整示例:

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

      【讨论】:

        猜你喜欢
        • 2019-07-31
        • 2022-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多