amir
amir

Reputation: 491

Ansible loop and print dictionary variable

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?

Upvotes: 1

Views: 5222

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68004

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"

Upvotes: 3

Maroun
Maroun

Reputation: 95948

If all you want to do is printing the dictionary items, you can do:

  - debug: msg="{{ item }}"
    with_items: "{{ dict_var | dict2items }}"

Upvotes: 0

Related Questions