在 Ansible 中,如何使用键的变量更改现有字典/哈希值 [英] In Ansible how do you change a existing dictionary/hash values using a variable for the key

查看:24
本文介绍了在 Ansible 中,如何使用键的变量更改现有字典/哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想根据对这个问题 我想出了下面的代码,但它不起作用,因为第二次调试调用中的值没有改变,我认为这是因为在另一个问题中他们正在从头开始创建一个新字典,但我也尝试过没有外部大括号,我认为这会导致它改变现有值.

As the title suggest i want to loop over an existing dictionary and change some values, based on the answer to this question i came up with the code below but it doesn't work as the values are unchanged in the second debug call, I'm thinking it is because in the other question they are creating a new dictionary from scratch, but I've also tried it without the outer curly bracket which i would have thought would have caused it to change the existing 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"

推荐答案

您不能更改现有变量,但可以注册一个同名的新变量.

You can not change existing variable, but you can register new one with the same name.

检查这个例子:

---
- 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"
        }
    }
}

这篇关于在 Ansible 中,如何使用键的变量更改现有字典/哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆