2

As the title says when I'd like to be able to pass a variable that is registered under one host group to another, but I'm not sure how to do that and I couldn't find anything relevant under the variable documentation http://docs.ansible.com/ansible/playbooks_variables.html

This is a simplified example of what I am trying to see. I have a playbook that calls many different groups and checks where a symlink points. I'd like to be able to report all of the symlink targets to console at the end of the play.

The problem is the registered value is only valid under the host group that it was defined in. Is there a proper way of exporting these variables?

---
- hosts: max_logger
  tasks:
    - shell: ls -la /home/ubuntu/apps/max-logger/active | awk -F':' '{print $NF}'
      register: max_logger_old_active

- hosts: max_data
  tasks:
    - shell: ls -la /home/ubuntu/apps/max-data/active | awk -F':' '{print $NF}'
      register: max_data_old_active

- hosts: "localhost"
  tasks:
  - debug: >
      msg="The old max_logger build is {{ max_logger_old_active.stdout }}
           The old max_data build is {{ max_data_old_active.stdout }}"
Brando__
  • 365
  • 6
  • 24

1 Answers1

6

You don't need to pass anything here (you just need to access). Registered variables are stored as host facts and they are stored in memory for the time the whole playbook is run, so you can access them from all subsequent plays.

This can be achieved using magic variable hostvars.

You need however to refer to a host name, which doesn't necessarily match the host group name (e.g. max_logger) which you posted in the question:

- hosts: "localhost"
  tasks:
  - debug: >
      msg="The old max_logger build is {{ hostvars['max_logger_host'].max_logger_old_active.stdout }}
           The old max_data build is {{ hostvars['max_data_host'].max_data_old_active.stdout }}"

You can also write hostvars['max_data_host']['max_data_old_active']['stdout'].

techraf
  • 64,883
  • 27
  • 193
  • 198
  • Followup question: Is there an easy way of specifying only the first host in a hostgroup in that format? I know about this command, but I don't know how that would necessarily fit in a command like you've suggested. ansible_play_hosts.index(inventory_hostname) == 0 – Brando__ Jul 14 '17 at 22:55
  • 1
    Please have a look at the attached link for other magic variables. And you can access the first element of a list using index `[0]`. – techraf Jul 14 '17 at 22:57
  • 2
    msg="The old max_logger build is {{ hostvars[groups['role_max_logger'][0]]['max_logger_old_active']['stdout'] }} on host {{ groups['role_max_logger'][0] }} Is what I ultimately needed. Thanks for the help – Brando__ Jul 14 '17 at 23:21
  • this is great! I wasted 4 hours trying to get this through the host when what I needed was the group. Thank you! – migueldavid Sep 03 '18 at 16:41