snippetpythonMinor
How to share variables across instances?
Viewed 0 times
sharehowinstancesvariablesacross
Problem
I'm writing TestInfra test scripts for mongo cluster instances using Molecule Ansible. I want to share variables across all the instances. I created a python class, and initialise and update the variables. Every time
How can I share variables across instances?
molecule verify, each test will run on each instance, so variables are independent on single instance.How can I share variables across instances?
Solution
Q: "Is it possible to share variables across instances?"
A: Yes. The dictionary hostvars keeps the variables. hostvars lets you access variables for another host, including facts that have been gathered about that host. You can access host variables at any point in a playbook. For example,
See:
-
Information about Ansible: magic variables
-
Scoping variables
-
Cache plugins
With “Fact Caching” disabled, to share information among Ansible playbooks, it's possible to store all hostvars in a file. For example, given the inventory
this template
and the playbook below
store hostvars of all hosts into the dictionary
my_hostvars_all and put it into the file
at localhost(master). The dictionary can be included in the next playbook. For example, the playbook
gives (abridged)
A: Yes. The dictionary hostvars keeps the variables. hostvars lets you access variables for another host, including facts that have been gathered about that host. You can access host variables at any point in a playbook. For example,
{{ hostvars['test.example.com']['ansible_facts']['distribution'] }}
See:
-
Information about Ansible: magic variables
-
Scoping variables
-
Cache plugins
With “Fact Caching” disabled, to share information among Ansible playbooks, it's possible to store all hostvars in a file. For example, given the inventory
shell> cat hosts
[test]
test_01
test_02
test_03
this template
shell> cat my_hostvars.json.j2
my_hostvars_all:
{% for my_host in ansible_play_hosts_all %}
{{ my_host }}:
{{ hostvars[my_host]|to_nice_json }}
{% endfor %}
and the playbook below
shell> cat pb1.yml
- hosts: test
tasks:
- set_fact:
test_var: "test_var_in_{{ inventory_hostname }}"
- template:
src: my_hostvars.json.j2
dest: "{{ playbook_dir }}/my_hostvars.json"
delegate_to: localhost
run_once: true
store hostvars of all hosts into the dictionary
my_hostvars_all and put it into the file
{{ playbook_dir }}/my_hostvars.json
at localhost(master). The dictionary can be included in the next playbook. For example, the playbook
shell> cat pb2.yml
- hosts: test
tasks:
- include_vars: my_hostvars.json
- debug:
msg: "{{ my_hostvars_all[inventory_hostname]['test_var'] }}"
gives (abridged)
ok: [test_01] =>
msg: test_var_in_test_01
ok: [test_02] =>
msg: test_var_in_test_02
ok: [test_03] =>
msg: test_var_in_test_03
Context
StackExchange DevOps Q#9068, answer score: 3
Revisions (0)
No revisions yet.