在Ansible中,如何使用键

时间:2018-02-16 11:15:24

标签: ansible ansible-2.x

由于标题建议我想循环现有的字典并更改一些值,根据这个question的答案,我提出了下面的代码,但它不起作用,因为值是在第二次调试调用中没有改变,我认为这是因为在另一个问题中他们是从头开始创建一个新的字典,但是我也尝试过没有外部花括号,我本以为会有导致它改变现有价值。

- set_fact:
  uber_dict:
    a_dict:
      some_key: "abc"
      another_key: "def"
    b_dict:
      some_key: "123"
      another_key: "456"

- debug: var="uber_dict"

- set_fact: "{ uber_dict['{{ item }}']['some_key'] : 'xyz' }"
  with_items: "{{ uber_dict }}"

- debug: var="uber_dict"

1 个答案:

答案 0 :(得分:5)

您无法更改现有变量,但您可以注册同名的新变量。

检查此示例:

---
- hosts: localhost
  gather_facts: no
  vars:
    uber_dict:
      a_dict:
        some_key: "abc"
        another_key: "def"
      b_dict:
        some_key: "123"
        another_key: "456"
  tasks:
    - set_fact:
        uber_dict: "{{ uber_dict | combine(new_item, recursive=true) }}"
      vars:
        new_item: "{ '{{ item.key }}': { 'some_key': 'some_value' } }"
      with_dict: "{{ uber_dict }}"
    - debug:
        msg: "{{ uber_dict }}"

结果:

ok: [localhost] => {
    "msg": {
        "a_dict": {
            "another_key": "def",
            "some_key": "some_value"
        },
        "b_dict": {
            "another_key": "456",
            "some_key": "some_value"
        }
    }
}