ansible 从字典中选择

ansible 从字典中选择

需要从字典变量中选择


- name: test 
  hosts: localhost

  vars:
      bum: 0
      alpha:
        - 0
      beta:
        - 0
        - 1
      test_vars: '{% if bum == 1 %}{{ alpha }}{% else %}{{ beta }}{% endif %}'
      servers:
        - 127.0.0.1
        - 127.0.0.2

  tasks:

  - debug:
      msg: "This is {{ item }}"
    loop:
      - "{{ test_vars }}"

  - ping: "{{ {{servers}} [{{ item }}] }}"
    loop:
      - "{{ test_vars }}"


谢谢

答案1

将逻辑放入字典中

    test_vars:
      1: "{{ alpha }}"
      default: "{{ beta }}"

并在循环中使用它

    - debug:
        msg: "item: {{ item }}"
      loop: "{{ test_vars[bum|int]|
                default(test_vars.default) }}"

用于测试的完整剧本示例

shell> cat pb.yml
- hosts: localhost

  vars:

    bum: 0
    alpha: [0]
    beta: [0, 1]
    test_vars:
      1: "{{ alpha }}"
      default: "{{ beta }}"

  tasks:

    - debug:
        msg: "item: {{ item }}"
      loop: "{{ test_vars[bum|int]|
                default(test_vars.default) }}"

默认情况下贝塔用来

shell> ansible-playbook pb.yml
...
TASK [debug] *********************************************************************************
ok: [localhost] => (item=0) => 
  msg: 'item: 0'
ok: [localhost] => (item=1) => 
  msg: 'item: 1'

您可以设置现有的密钥,例如

shell> ansible-playbook pb.yml -e bum=1
...
TASK [debug] *********************************************************************************
ok: [localhost] => (item=0) => 
  msg: 'item: 0'

相关内容