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 }}"
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With