首页 > 解决方案 > Ansible 中的关联数组更新

问题描述

我在ansible中有这样的变量:

var:
    param:
        key.something: value

我想更新“key.something”。我怎样才能做到这一点?

这(如我所料)不起作用:

- name: Update param
  set_fact:
     var.param['key.something']: "value2"

标签: ansible

解决方案


Ansible 无法“更新”变量。您只能创建新变量。在许多情况下,您可以通过使用set_factcombine过滤器将目标变量替换为新变量来获得所需的内容。

例如,如果我有:

- hosts: localhost
  gather_facts: false
  vars:
    target:
      somekey: somevalue

我可以编写一个任务来“更新”这样的值somekey

  tasks:
    - name: update somekey in target
      set_fact:
        target: "{{ target | combine({'somekey': 'newvalue'}) }}"

在您的问题中,您正在尝试更改深度嵌套的键而不是顶级键。combine过滤器有一个选项recursive可以在这种情况下提供帮助:

- hosts: localhost
  gather_facts: false
  vars:
    target:
      key1: value1
      param:
        key2: value2
        key3: value3

  tasks:
    - name: update nested key in target
      set_fact:
        target: "{{ target | combine({'param': {'key3': 'anothervalue'}}, recursive=true) }}"

    - debug:
        var: target

如果我们运行这个剧本,我们会得到:


PLAY [localhost] *************************************************************************************************************************************************************

TASK [set_fact] **************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
    "target": {
        "key1": "value1",
        "param": {
            "key2": "value2",
            "key3": "anothervalue"
        }
    }
}

PLAY RECAP *******************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

推荐阅读