4

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 molecule verify, each test will run on each instance, so variables are independent on single instance.

How can I share variables across instances?

Pierre.Vriens
  • 7,225
  • 14
  • 39
  • 84
Abel
  • 141
  • 2

1 Answers1

3

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,

{{ hostvars['test.example.com']['ansible_facts']['distribution'] }}

See:


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
Vladimir Botka
  • 2,081
  • 8
  • 12