Ansible - Updating nested variables

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"


Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |