Search code examples
ansibleansible-inventory

Ansible play runs on one group of hosts, but depends on facts from others


Here's the basic use case:

I have an NGINX reverse proxy I want to set up and so I specific a play that only runs on the "nginx" group.

However, in order to know the ips to reverse proxy to I need to gather facts from the "upstreams" group. This doesn't happen since the play does not run setup on the "upstreams".

This answer contains a solution I've used before, but I'd like to be able to have it all self contained in a single hosts play that I can run independently of others.


Solution

  • Use Delegated Facts, pre_tasks, and delegate the facts to the hosts they belong to.

    - hosts: nginx
      become: yes
      tags:
        - nginx
      vars:
        listen_address: "x.x.x.x"
      pre_tasks:
        - name: 'gather upstream facts.'
          setup:
          delegate_to: "{{item}}"
          delegate_facts: True
          with_items: "{{groups['upstreams']}}"
      roles:
        - role: nginx
          upstreams: "{{ groups['upstreams'] | map('extract', hostvars, ['ansible_all_ipv4_addresses']) | ipaddr('x.x.x.x') | first | list }}"