Techiio-author
Started by Peter DanielsSep 24, 2021

Open
How to create dynamic variables in ansible

1 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWES SHARE

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?

1 Replies

Techiio-commentatorNeel Dey replied 5 months ago0 likes0 dislikes

If you're gathering facts, you can access host vars 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 host vars. 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.

You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance