Jinja2: How to gather_facts from other hosts

If you have this content in your inventory file:

ha01 ansible_host=ec2-52-50-164-246.eu-west-1.compute.amazonaws.com
ha02 ansible_host=ec2-52-48-101-228.eu-west-1.compute.amazonaws.com

web01 ansible_host=ec2-52-50-143-215.eu-west-1.compute.amazonaws.com
web02 ansible_host=ec2-52-31-14-253.eu-west-1.compute.amazonaws.com

And you want to create a template inside your loadbalancers with information from webservers, like for example following haproxy configuration:

{% for host in groups['webservers'] %}
server {{ hostvars[host]['ansible_hostname'] }} {{ hostvars[host]['ansible_default_ipv4']['address'] }}:80
{% endfor %}

You first need to connect to webservers. No need to do anything. So, your playbook will look like:

# No need to run a task for webservers. This will gather their facts.
- hosts: webservers
  become: yes

- hosts: loadbalancers
  become: yes
- haproxy-ha

This will connect first to your webservers and gather their facts that will be used in haproxy.cfg.j2 template file.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s