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

查看:69
本文介绍了在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天全站免登陆