Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update nested variables in Ansible

Tags:

python

ansible

I have some extra information like db connection details etc. stored in /etc/ansible/facts.d/environment.fact.

These are made available as variables like ansible_local.environment.database.name. What is the best way to update the database name?

I tried the set_fact module but could not get it to update the nested variable correctly. It just overwrites the whole ansible_local hash.

- name: Update database name
  set_fact:
  args:
    ansible_local:
      environment:
        database:
          name: "{{ db_name }}"
like image 214
Mikhail Janowski Avatar asked May 05 '16 06:05

Mikhail Janowski


People also ask

How do you pass multiple vars in ansible?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

How do you pass variables in ansible playbook?

The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.

What is Hostvars ansible?

With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.


2 Answers

This should help, assuming you are using Ansible 2.0 or older.

- set_fact:
    test:
      app:
        in: 1
        out: 2

- set_fact:
    test_new:
      app:
        transform: 3

- set_fact:
    test: "{{test|combine(test_new,recursive=True)}}"

- debug: var=test

A combine is a Jinja2 filter included with Ansible. Make sure you are using recursive parameter in such cases.

like image 95
wst Avatar answered Sep 16 '22 20:09

wst


That's default Ansible behaviour -- override whole hash when changing part of it. See ansible.conf:

# if inventory variables overlap, does the higher precedence one win
# or are hash values merged together?  The default is 'replace' but
# this can also be set to 'merge'.
#hash_behaviour = replace

So if you change it to hash_behaviour = merge it will work as you expect.

like image 39
anlar Avatar answered Sep 18 '22 20:09

anlar