can you use set_fact to save information about HOSTX and then later in a different play, retrieve from HOSTY?

60 views
Skip to first unread message

markpat...@gmail.com

unread,
Mar 8, 2016, 1:32:32 PM3/8/16
to Ansible Project
HI there.

I've been playing around with ansible for the past few days and I have run across a question.
I need a way to set a value on host x ... and then have that information available to host y.
Notice the playbook below:

- hosts: group1
  tasks:
  - name: count reg on primary
    shell: psql -U widgets widgets -c 'SELECT COUNT(*) FROM location' -t
    register: result
  - debug: var=result.stdout
  - set_fact: the_count={{result.stdout}} 
  - debug: var={{the_count}}

- hosts: group2
  tasks:
  - name: retrieve variable from previous play
    shell: echo hello
  - debug: var={{hostvars}}   

When I run this, this is the output i get ... in part:

TASK [set_fact] ****************************************************************
ok: [myserver1.mydomain.com]

TASK [debug] *******************************************************************
ok: [myserver1.mydomain.com] => {
    "the_count": "     2"
}

PLAY ***************************************************************************

TASK [retrieve variable from previous play] ************************************
changed: [myserver1.mydomain.com]
changed: [myserver2.mydomain.com]

TASK [debug] *******************************************************************
ok: [myserver1.mydomain.com] => {
    "<ansible.vars.hostvars.HostVars object at 0x7fa8cff5c1d0>": "VARIABLE IS NOT DEFINED!"
}
ok: [myserver2.mydomain.com] => {
    "<ansible.vars.hostvars.HostVars object at 0x7fa8cff5c1d0>": "VARIABLE IS NOT DEFINED!"
}

As you can see, in the first play, the variable seems to be set correctly in the sense that I can query "the_count" and see that the value is 2.
However, once I hit the second play, I am unable to retrieve the value. "group1" only contains myserver1.  Group2 includes myserver1 and myserver2 as you can see from the output.
Myserver2 will not have "the_count" set, so I understand why I'm getting the error message about the variable not being defined. 

But why is this the case for server1?

Ultimately, i need to be able to change my hosts file so that "group2" only includes myserver2.  Should this code still work in that scenario?

I've been reading http://docs.ansible.com/ansible/set_fact_module.html but I wasn't able to find any examples similar to what I'm trying to accomplish.
Perhaps I'm using the wrong function.

Any help would be appreciated.
Reply all
Reply to author
Forward
0 new messages