Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible playbook-wide variable

I have a playbook with multiple hosts section. I would like to define a variable in this playbook.yml file that applies only within the file, for example:

vars:
  my_global_var: 'hello'

- hosts: db
  tasks:
   -shell: echo {{my_global_var}} 

- hosts: web
  tasks:
   -shell: echo {{my_global_var}} 

The example above does not work. I have to either duplicate the variable for each host section (bad) or define it at higher level, for example in my group_vars/all (not what I want, but works). I am also aware that variables files can be included, but this affects readibility. Any suggestion to get it in the right scope (e.g the playbook file itself)?

like image 262
Hristo Stoyanov Avatar asked Nov 30 '15 05:11

Hristo Stoyanov


People also ask

How do you pass multiple extra variables in Ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

How do you pass variables in Ansible playbook?

The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.

How are global variables defined in Ansible?

Variable Scopes Ansible has 3 main scopes: Global: this is set by config, environment variables and the command line. Play: each play and contained structures, vars entries, include_vars, role defaults and vars. Host: variables directly associated to a host, like inventory, facts or registered task outputs.


2 Answers

The set_fact module will accomplish this if group_vars don't suit your needs.

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html

This module allows setting new variables. Variables are set on a host-by-host >basis just like facts discovered by the setup module. These variables will >survive between plays during an Ansible run, but will not be saved across >executions even if you use a fact cache.

- hosts: db:web
  tasks:
  - set_fact: my_global_var='hello'

- hosts: db
  tasks:
  -shell: echo {{my_global_var}} 

- hosts: web
  tasks:
  -shell: echo {{my_global_var}} 
like image 127
smeagol Avatar answered Oct 25 '22 17:10

smeagol


I prefer to keep global variables in the inventory file, where you keep the groups and names of your hosts.

For example:

my-hosts:

[all:vars]
my_global_var="hello"

[db]
db1
db2
[web]
web1
web2

Run your playbook with:

ansible-playbook -i my-hosts playbook.yml

The variable will now be defined for all hosts.

If you are using ec2.py or some other dynamic inventory, you can put the global variables in the file group_vars/all to achieve the same result.

like image 36
jonatan Avatar answered Oct 25 '22 18:10

jonatan