I’m trying to dynamically build the group of hosts that will be used in a play. I’m doing this within a hosts: localhost play. However hostvars seems to be undefined when evaluating the - hosts: line. Suggestions?
Not being helpful, but re-enforcing the (mis)behaviour using Ansible 2.0.2
For my case I was calling sts_assume_role on localhost (hosts:localhost) for get a different aws id, key and token seeing it’s only an api call, then setting then using set_facts to set variables. In another play in the same playbook I called it against another host (host:foobar) and tried to reference hostvars[‘localhost’][‘aws_cred_id’] .The variable is not defined was my result.
I managed to work around it just by calling the sts_assume_role task on the remote host.
Is this the expected behaviour? I thought magic variables could be used for this? is it only for retrieving group file variables?
Thanks Steve. This sounds very much like what I’m trying to do. In my case I want to enforce some rules, defaults and aliases on a host group selected via --extra-vars. Thought I would do that with a localhost Play and set_facts, as you described. If this is the wrong approach I’m happy to get steered in the right direction. I started looking at dynamic inventory but this seems to be overkill for my current need. It also feels like the wrong direction. Another option I’m considering is a jinja2 function. Eg. - hosts: "{{ myj2func() }}
Just want to make sure you’ve considered add_host
http://docs.ansible.com/ansible/add_host_module.html
Hmm, looks promising but seems to be the opposite of what I want. I would want to create a new group ID that references an existing group. Another solution would be to dynamically create an extra-var or similar root/global scoped variable. Is there anything like set_extra_var with behaviour similar to set_fact? This is pushing back toward the functionality that works:
- hosts: “{{ extra_var }}” I tested this and it works
- hosts: “{{ dynamically_created_extra_var }}” Does this exist?