Warm tip: This article is reproduced from serverfault.com, please click

Ansible loop and print dictionary variable

发布于 2020-11-29 09:38:55

Can anyone help with this basic question? I have a dictionary variable and I'd like to print it.

dict_var:
  - key1: "val1"
  - key2: "val2"  
  - key3: "val3"

Is it possible to loop and print its content in a playbook?

Questioner
amir
Viewed
11
Vladimir Botka 2020-11-29 19:25:03

Q: "Loop and print variable's content."

A: The variable dict_var is a list. Loop the list, for example

- hosts: localhost
  vars:
    dict_var:
      - key1: "val1"
      - key2: "val2"
      - key3: "val3"
  tasks:
    - debug:
        var: item
      loop: "{{ dict_var }}"

gives (abridged)

    "item": {
        "key1": "val1"
    }

    "item": {
        "key2": "val2"
    }

    "item": {
        "key3": "val3"
    }

Q: "Loop and print dictionary."

A: There are more options when the variable is a dictionary. For example, use dict2items to "loop and have key pair values in variables" item.key and item.value

- hosts: localhost
  vars:
    dict_var:
      key1: "val1"
      key2: "val2"
      key3: "val3"
  tasks:
    - debug:
        var: item
      loop: "{{ dict_var|dict2items }}"

gives (abridged)

    "item": {
        "key": "key1",
        "value": "val1"
    }

    "item": {
        "key": "key2",
        "value": "val2"
    }

    "item": {
        "key": "key3",
        "value": "val3"
    }

The next option is to loop the list of the dictionary's keys. For example

    - debug:
        msg: "{{ item }} {{ dict_var[item] }}"
      loop: "{{ dict_var.keys()|list }}"

gives (abridged)

    "msg": "key1 val1"

    "msg": "key2 val2"

    "msg": "key3 val3"