首页 > 解决方案 > Ansible 循环和打印字典变量

问题描述

任何人都可以帮助解决这个基本问题吗?我有一个字典变量,我想打印它。

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

是否可以在剧本中循环和打印其内容?

标签: ansible

解决方案


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"

推荐阅读