Oskar Gunther
Oskar Gunther

Reputation: 59

Associative array update in Ansible

I've got variable in ansible like this:

var:
    param:
        key.something: value

And I want to update "key.something". How can I do this?

This (as I expected) doesn't work:

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

Upvotes: 2

Views: 1865

Answers (1)

larsks
larsks

Reputation: 312490

Ansible isn't able to "update" variables. You can only create new variables. In many cases you can get what you want by replacing your target variable with a new one using set_fact and the combine filter.

For example, if I have:

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

I can write a task that will "update" the value of somekey like this:

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

In your question, you're trying to change a deeply nested key rather than a top-level key. The combine filter has a recursive option to help in that situation:

- 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

If we run this playbook, we get:


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   

Upvotes: 3

Related Questions