Ansible: Use variable for defining playbook hosts

Vetemi picture Vetemi · Dec 6, 2016 · Viewed 10k times · Source

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.

Answer

Konstantin Suvorov picture Konstantin Suvorov · Dec 6, 2016

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.