Answer the question
In order to leave comments, you need to log in
Ansible: how to extract the ip-address of the host with which the interaction is going on in a variable?
Good afternoon. In the process of getting to know Ansible (2.9.2), I solve a practical problem - generating a zabbix agent config for a group of typical machines (Debian 10). In the j2-template of the config, only one variable is planned. This is the listen ip. There can be many network interfaces on remote machines (thousands) and I would really not like to execute the gether_facts procedure completely, but limit myself to some subset of the env type. In addition, even if I get a complete list of interfaces, it is not clear what logic to use to isolate exactly the ip-address that I need. Basically, all I need is to get a variable containing the IP address of the SSH server that Ansible is currently communicating with. In the process of googling, I came across an article where my case was described exactly. And there are three approaches to solving the problem:
https://www.middlewareinventory.com/blog/ansible-g...
I decided to stick with method #1:
---
- hosts: all
gather_facts: yes
tasks:
- debug: var=hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2]
TASK [debug] *********************************************************************************************************************************************************************************
ok: [host1] => {
"hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2]": "VARIABLE IS NOT DEFINED!"
}
---
- hosts: my_group
become: true
gather_facts: yes
pre_tasks:
- setup:
gather_subset: 'all'
tasks:
- debug: var=hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2]
Answer the question
In order to leave comments, you need to log in
It turned out that the execution by hand through the ansible binary on the localhost (ansible localhost -m setup -a 'gather_subset=min') is what you need. After I carefully re-read the output of my playbook and compared it with what I received before, it turned out that become: true interferes with the process of obtaining an IP. The resulting playbook looks like this:
---
- hosts: localhost
become: false
gather_facts: no
pre_tasks:
- setup:
gather_subset: 'min'
tasks:
- debug: var=hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question