1

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?

0

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

THank you for your message :) Basically, print is the first step. Later, I would like to use them and for example build another variable using the values. Would it be possible to loop and have key pair values in a variable ?
Besides, I get a message when trying your solution: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\n

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.