How to loop over this dictionary in Ansible?

前端 未结 5 597
说谎
说谎 2020-12-02 22:59

Say I have this dictionary

war_files:
  server1:
  - file1.war
  - file2.war
  server2:
  - file1.war
  - file2.war
  - file3.war

and for n

5条回答
  •  温柔的废话
    2020-12-02 23:46

    Here is my preferred way to loop over dictionaries:

    input_data.yml contains the following:

    ----
    input_data:
      item_1:
        id: 1
        info: "Info field number 1"
      item_2:
        id: 2
        info: "Info field number 2"
    

    I then use a data structure like the above in a play using the keys() function and iterate over the data using with_items:

    ---
    - hosts: localhost
      gather_facts: false
      connection: local
      tasks:
        - name: Include dictionary data
          include_vars:
            file: data.yml
    
        - name: Show info field from data.yml
          debug:
            msg: "Id: {{ input_data[item]['id'] }} - info: {{ input_data[item]['info'] }}"
          with_items: "{{ input_data.keys() | list }}"
    

    The above playbook produces the following output:

    PLAY [localhost] ***********************************************************
    
    TASK [Include dictionary data] *********************************************
    ok: [localhost]
    
    TASK [Show info field from data.yml] ***************************************
    ok: [localhost] => (item=item_2) => {
        "msg": "Id: 2 - info: Info field item 2"
    }
    ok: [localhost] => (item=item_3) => {
        "msg": "Id: 3 - info: Info field item 3"
    }
    ok: [localhost] => (item=item_1) => {
        "msg": "Id: 1 - info: Info field item 1"
    }
    
    PLAY RECAP *****************************************************************
    localhost                  : ok=2    changed=0    unreachable=0    failed=0
    

提交回复
热议问题