How to create dynamic variables in ansible

Lakshman Diwaakar picture Lakshman Diwaakar · Sep 3, 2015 · Viewed 27.9k times · Source

The real scenario, want to get a resource id of sqs in AWS, which will be returned after the execution of a playbook. So, using this variable in files to configure the application.

Persisting variables from one playbook to another

checking out the documentation, modules like set_fact and register have scope only for that specific host. There are many purpose of using the variables from one host to another.

Alternatives I can think of:

  1. using Command module and echoing the variables to a file. Later, using the variable file using vars section or include.

  2. Setting the env variables and then accessing it but this will be difficult.

So what is the solution?

Answer

user559633 picture user559633 · Sep 3, 2015

If you're gathering facts, you can access hostvars via the normal jinja2 + variable lookup:

e.g.

- hosts: serverA.example.org
  gather_facts: True
  ...
  tasks:

    - set_fact:
        taco_tuesday: False 

and then, if this has run, on another host:

- hosts: serverB.example.org
  ...
  tasks:

    - debug: var="{{ hostvars['serverA.example.org']['ansible_memtotal_mb'] }}"

    - debug: var="{{ hostvars['serverA.example.org']['taco_tuesday'] }}"

Keep in mind that if you have multiple Ansible control machines (where you call ansible and ansible-playbook from), you should take advantage of the fact that Ansible can store its facts/variables in a cache (currently Redis and json), that way the control machines are less likely to have different hostvars. With this, you could set your control machines to use a file in a shared folder (which has its risks -- what if two control machines are running on the same host at the same time?), or set/get facts from a Redis server.

For my uses of Amazon data, I prefer to just fetch the resource each time using a tag/metadata lookup. I wrote an Ansible plugin that allows me to do this a little more easily as I prefer this to thinking about hostvars and run ordering (but your mileage may vary).