I’m doing some cloud scripting that involves some work on one host, then using the results to take action on another host. The hostname of the second host is a dynamic result of that first bit, and won’t be in my inventory. I’d like to do as much of it as possible in ansible, and add_host
seems to be working. But I’m having trouble using a variable or fact from one play as the hosts
value for the next play.
Here’s a test case that I’ve been working on: I’ve made it as simple as possible.
test.yml
-
hosts: 127.0.0.1
tasks: -
set_fact: hostname_test=‘fubar’
-
add_host: name=‘{{ hostname_test }}’
register: resp -
debug: msg=‘{{ resp }}’
-
hosts: 127.0.0.1
tasks: -
debug: msg=‘resp={{ resp|default(“None”) }}’
-
debug: msg=‘hostname_test={{ hostname_test|default(“None”) }}’
end
I’d like that second play to start with - hosts: hostname_test
. But that results in “skipping: no hosts matched”. At first I thought that meant add_host
wasn’t working. But if I hardcode hosts: fubar
for the second play then ansible tries to connect as expected. However I need to determine the second hostname as part of the first play. Running the code as above suggests that neither set_fact
nor register
persists from the first play to the next: both seem to be undefined.
Is it possible to use a hostname determined in one play as the hosts value for the next play? If so, what am I doing wrong? Is there a better way to persist new information from one play to the next?
Is it significant that ansible reports the first play under 127.0.0.1
, as in the yml, but the second play shifts to localhost
?
Thanks in advance for any help.
$ ansible --version
ansible 1.8.4
configured module search path = None
$ ansible-playbook -v test.yml
PLAY [127.0.0.1] **************************************************************
GATHERING FACTS ***************************************************************
ok: [127.0.0.1]
TASK: [set_fact hostname_test=‘fubar’] ****************************************
ok: [127.0.0.1] => {“ansible_facts”: {“hostname_test”: “fubar”}}
TASK: [add_host name=‘{{ hostname_test }}’] ***********************************
ok: [127.0.0.1] => {“new_host”: “fubar”}
TASK: [debug msg=‘{{ resp }}’] ************************************************
ok: [127.0.0.1] => {
“msg”: “{‘invocation’: {‘module_name’: u’add_host’, ‘module_args’: u"name=‘fubar’"}, ‘new_host’: u’fubar’}”
}
PLAY [127.0.0.1] **************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [debug msg=‘resp=None’] *************************************************
ok: [localhost] => {
“msg”: “resp=None”
}
TASK: [debug msg=‘hostname_test=None’] ****************************************
ok: [localhost] => {
“msg”: “hostname_test=None”
}
PLAY RECAP ********************************************************************
127.0.0.1 : ok=4 changed=0 unreachable=0 failed=0
localhost : ok=3 changed=0 unreachable=0 failed=0