Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using register variable to store values for multi host play

Tags:

ansible

I have an ansible playbook which contains two plays, the output of first play is to be used by the second. So I'm using register variable to store the output. The problem is my play is intended to work on multi hosts rather than single host and the output of register is overridden each time and I don't have the values for last (n-1) executions.

My playbook looks like this:

- name: Perform task 
  hosts:  db_server
  connection: local
  gather_facts: no
  vars:
    - method: "{{ method }}"

  roles:
    - {role: run_custom_module, tags: ["maintenance"]}


- name: Second task based on output of first
  hosts:  db_server
  connection: local
  gather_facts: no
  vars:
    - method: "{{ method }}"

  roles:
    - {role: run_custom_module, when: result=="some_string"}

The role run_custom_module looks like this:

- name: Executing the custom module
  run_custom_module:
      task: "Run custom py module"
      var: "{{ method }}"
  register: result

The inventory file looks like:

[db_server]
1.1.1.1
2.2.2.2
3.3.3.3

In case of with_items, the register variable store the output in a list called results, refer here. On similar grounds, how can I store the output of multi host play in the register variable so that it can be used in second play of the same playbook?

like image 564
Naman Arora Avatar asked Jun 20 '17 08:06

Naman Arora


1 Answers

Registered variables are facts. You can access facts on other hosts with hostvars.

For instance, you could access result registered variable for host 1.1.1.1 with hostvars['1.1.1.1'].result.

You can list all hosts in a group with groups.

For instance, you could list all hosts in db_server group with groups['db_server'].

To wrap things up, you could try something like this :

---
- hosts: db_server
  tasks:
    - ping:
      register: result

    - debug: var=hostvars[item].result
      with_items: "{{ groups['db_server'] }}"
like image 83
Eric Citaire Avatar answered Nov 08 '22 22:11

Eric Citaire