Ansible: use a variable to define hosts

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

I want to specify my host variable as an external variable, and then use it in a playbook like this:

hosts: "{{integration}}" 

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

 integration: "int60" 

The host file is as follows:

 [int60] hostA [int61] hostB 

Unfortunately this will not work. I also tried to define host var as follows:

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

and the integration_env parameter is specified in the group_vars / all file. In this case, it seemed that he ran tasks locally, and not in the desired environment.

Is it possible to do something like this? I would be open to all new ways to do this. The main goal is to simply define the host variable in the var file.

+6
source share
1 answer

This will work if you pass the integration variable as an additional variable:

 ansible-playbook -e integration=int60 myplaybook.yml 

Any variables used in the title of the play must be defined before Ansible parses the playbook.

In your example, you define integration as host facts. Facts are determined only at the level of the task, and not at the level of reproduction.

Update: and you can use other ways of passing variables, and not just additional vars. For instance:

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

will also work.

+7
source

Source: https://habr.com/ru/post/1012934/


All Articles