在 Ansible 中,如何使用键变量更改现有的 dictionary/hash 值
In Ansible how do you change a existing dictionary/hash values using a variable for the key
正如标题所暗示的那样,我想遍历现有字典并更改一些值,基于对此问题的回答 我想出了下面的代码,但它不起作用,因为值是在第二次调试调用中没有变化,我认为这是因为在另一个问题中他们正在从头开始创建一个新字典,但我也尝试过没有外部大括号,我认为这会导致它改变现有值。
- 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"
您不能更改现有变量,但您可以注册一个同名的新变量。
检查这个例子:
---
- 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"
}
}
}
正如标题所暗示的那样,我想遍历现有字典并更改一些值,基于对此问题的回答
- 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"
您不能更改现有变量,但您可以注册一个同名的新变量。
检查这个例子:
---
- 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"
}
}
}