Bootstrap FreeKB - Ansible - Updating nested variables
Ansible - Updating nested variables

Updated:   |  Ansible articles

Let's say you have the following nested variables.

---
- hosts: all
  vars: 
    food:
      fruit: "Apple"
      veggy: "Onion"

 

The debug module can be used to print the value of the "fruit" variable.

- name: output the nested 'food.fruit' variable
  debug:
    var: food.fruit

 

Which should return something like this.

ok: [server1.example.com] => {
    "food.fruit": "Apple"
}

 

The set_fact module can be used to update the "fruit" variable to contain a value of "Banana".

- set_fact:
    food:
      fruit: "Banana"

 

Or you could update the "fruit" variable to contain a value of "Banana" like this.

- name: update the 'fruit' variable to contain a value of 'banana'
  set_fact:
    food: "{{ food | combine( { 'fruit': 'Banana' }, recursive=True ) }}"

 

Now when you print the "fruit" variable, something like this should be returned.

ok: [server1.example.com] => {
    "food.fruit": "Banana"
}

 


Updating nested variables in a file

Let's say users.yml contains the following nested variables.

john:
  foo: "bar"
jane:
  foo: "bar"

 

This playbook will update the users.yml file so that only the john.foo nested variable contains Hello World.

---
- hosts: all
  tasks:
    - command: echo Hello World
      register: out

    - include_vars:
        file: vars.yaml
        name: _dict

    - copy:
        content: |
          {{ _dict_update|to_nice_yaml }}
        dest: users.yaml
      vars:
        _value: "{{ _dict.john|combine({'foo': out.stdout}) }}"
        _dict_update: "{{ _dict|combine({'john': _value}) }}"
...

 

Now users.yml should contain the following nested variables.

john:
  foo: "Hello World"
jane:
  foo: "bar"



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 4e3d63 in the box below so that we can be sure you are a human.