11

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.

Vetemi
  • 784
  • 2
  • 9
  • 26

1 Answers1

12

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.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Thanks for your quick answer. I've seen solutions like that but this won't work for me because I'm running ansible through a jenkins job (and a ansible plugin) which doesn't allow to pass any extra variable. Also, I would need to change the integration variable in a ansible task, so that the next run would pick up a different environment. Do you know other solutions? – Vetemi Dec 06 '16 at 10:43
  • The jenkins ansible plugin does allow extra variables. It's hidden under the 'advanced' options when creating the Ansible step in Jenkins. – Steve E. Dec 06 '16 at 11:34
  • @ Steve: Yes, you're right but I need to change this variable via ansible tasks, so this solution wouldn't work for me. – Vetemi Dec 13 '16 at 08:42
  • @Konstantin: Storing the variable in an environment variable is a valid solution (e.g. export the stored ansible variable to environment variable in a previous task and use it afterwards) but a direct use of the variable would be better. So my question is: Is that even possibe? – Vetemi Dec 13 '16 at 08:48
  • No, the only way to influence next play's hosts from previous tasks, is dynamic groups. You hardcode static group name to your play and populate it during previous play. See http://stackoverflow.com/a/38631923/2795592 – Konstantin Suvorov Dec 13 '16 at 08:55