Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Use variable for defining playbook hosts

I have the following version installed: ansible 2.3.0 (devel 2131eaba0c)

I want to specify my host variable as external variable and then use it in the playbook similar to this:

hosts: "{{integration}}"

In my group_vars/all file I have the following defined variable:

integration: "int60"

The host file looks like this:

[int60] 
hostA

[int61]
hostB

Unfortunately this does not work. I also tried to define the host var in the following way:

[integration]
127.0.0.1 ansible_host="{{ integration_env }}"

and have the integration_env specified in my group_vars/all file. In this case it seemed like it ran the tasks locally and not in the desired environment.

Is it possible to do something like this? I'd be open to whole new ways of doing this. The main goal is simply to define the host variable in a var file.

like image 327
Vetemi Avatar asked Dec 06 '16 10:12

Vetemi


People also ask

How do you use Ansible variables in playbook?

Ansible uses variables to manage differences between systems. With Ansible, you can execute tasks and playbooks on multiple different systems with a single command. To represent the variations among those different systems, you can create variables with standard YAML syntax, including lists and dictionaries.

What is used to identify hosts in Ansible?

nmap inventory – Uses nmap to find hosts to target — Ansible Documentation.

Which argument will you use to specify a variable for Ansible playbook?

It is possible to set variables at the command line using the –extra-vars (or -e) argument.


1 Answers

This will work if you pass integration variable as extra variable:

ansible-playbook -e integration=int60 myplaybook.yml

Any variables used in play "header", should be defined before Ansible parses playbook.

In your example you define integration as host facts. Facts are only defined on task level, not play level.

Update: and you can use other ways of passing variables, not only extra vars. For example:

- hosts: "{{ lookup('env','DYN_HOSTS') }}"

will also work.

like image 117
Konstantin Suvorov Avatar answered Dec 12 '22 08:12

Konstantin Suvorov