Ansible run global variable

ansibleansible-playbook

I want to create a cluster of servers, using ansible.

In one main-playbook, I include some sub-playbooks.

- include: playbook_commandserver.yml
- include: playbook_agent.yml

In the playbook_commandserver.yml, I create the command-server (on aws).
Then, I trigger a role, that uses the set_fact module to remember the commandserver's dns name:

- name: Get hostname of command server
  shell: /usr/bin/host $(/usr/bin/curl -s http://ipecho.net/plain) | /usr/bin/awk '{print $5}' | /usr/bin/awk -F 'aws.com' '{print $1"aws.com"}'
  register: cs
- name: Set hostname of command server as fact
  set_fact: commandserver="{{ cs.stdout }}"

The commandserver fact is available in the same play, but not in the same playbook .. let alone in the playbook_agent.yml, that gets included, afterwards. And it's exactly there, where I would need to access that commandserver-fact.

So how does one set/store variables, that are valid for the complete ansible-run?

I've found this:
https://stackoverflow.com/questions/26732241/ansible-save-registered-variable-to-file
However to me this looks like an ugly hack.

Is ther no better solution to this problem?
Is there no way to set a variable, that is valid for the whole ansible-run?

Best Answer

Yes, this is possible. When you set a fact with the set_fact module, this fact is accessible via "hostvars". So if you define your variable commandserver like so:

  - name: Set hostname of command server as fact
    set_fact: commandserver="{{ cs.stdout }}"

then you can access this variable in other included playbooks of the same play in that way (the debug module is just an example):

  - debug: msg="{{ hostvars['put the hostname in here']['commandserver'] }}"