How do I get the IP address of a host based on variables?
I would like to get the IP address of a given host in my inventory based on the variables it has.
the hosts
[pgsql_servers]
psql-01 ansible_host=10.11.12.13 pg_master=True pg_slave=False
psql-02 ansible_host=10.11.12.14 pg_master=False pg_slave=True
psql-03 ansible_host=10.11.12.15 pg_master=False pg_slave=True
[pgsql_servers:vars]
ansible_python_interpreter=/usr/bin/python3
So, in my slave tasks that only run for slaves, I would like to get the IP address of a single master.
slave-tasks.yml
- name: Replicate data from Master
command: repmgr -h HOW_TO_GET_MASTER-IP_HERE -U repmgr -d repmgr -D /var/lib/postgresql/9.5/main -f /etc/repmgr.conf standby clone
become: true
become_user: postgres
I thought of adding when
here, but the master won't get into slave-tasks.yml
, so it never will True
. Any ideas on how to manage this?
source to share
You can get the master without defining an additional variable (which is prone to copy errors):
- name: Replicate data from Master
command: repmgr -h {{ master_ip }} -U repmgr -d repmgr -D /var/lib/postgresql/9.5/main -f /etc/repmgr.conf standby clone
become: true
become_user: postgres
vars:
master_ip: "{{ hostvars | json_query('* | [?pg_master] | [0].ansible_host') }}"
json_query:
* - take all values of current dictionary as a list
[?pg_master] - select only elements that evaluate pg_master key as true
[0].ansible_host - select ansible_host of the first element
source to share
Simple. Just add another variable in hosts
as pg_master_ip
with the master IP address and use it in slave-tasks.yml
, for example
- name: Replicate data from Master
command: repmgr -h {{ pg_master_ip }} -U repmgr -d repmgr -D /var/lib/postgresql/9.5/main -f /etc/repmgr.conf standby clone
become: true
become_user: postgres
source to share