How to persist variables/facts in ansible?

278 views
Skip to first unread message

Diwaakartg Ganesh

unread,
Sep 3, 2015, 8:13:50 AM9/3/15
to Ansible Project

checking out the documentation, modules like set_fact and register have scope only for that specific host. There are many purpose of using the variables from one host to another.

Alternatives I can think of:

  1. using Command module and echoing the variables to a file. Later, using the variable file using vars section or include.

  2. Setting the env variables and then accessing it but this will be difficult.

So what is the solution?

Takeshi Yaegashi

unread,
Sep 5, 2015, 2:29:09 AM9/5/15
to Ansible Project
Hello,

You can use hostvars[hostname] to get facts set by other hosts.  play_hosts array is also useful. 

The following playbook collects root's SSH public keys from all hosts, then distributes keys back to all hosts.

---
- hosts: all
  sudo
: yes
  gather_facts
: no
  vars
:
    pubkeys
: |
     
{%- for i in play_hosts %}
     
{%-   set k = hostvars[i].pubkey %}
     
{%-   if k %}
     
{{      k }}
     
{%    endif %}
     
{%- endfor %}
  tasks
:
   
- command: cat /root/.ssh/id_rsa.pub
     
register: r
      failed_when
: false
   
- set_fact:
        pubkey
: "{{ r.stdout | default('') }}"
   
- debug:
       
var: pubkeys
   
- authorized_key:
        user
: root
        key
: "{{ pubkeys }}"

Possible improvement: it would be nice if this playbook could also distribute all host keys into /root/.ssh/known_hosts of each host.

Regards,
-- 
YAEGASHI Takeshi <yaeg...@debian.org
Reply all
Reply to author
Forward
0 new messages