Ansible – Retrieve IP Address for Given Network Interface

ansiblenetworking

I am currently facing an issue with my ansible role, actually my ansible role installed NRPE server on Linux.

In some case, those servers have multiple NIC and need to bind the NRPE server to one particular NIC (dedicated for the monitoring network).

My goal is to retrieve the IP address of a named network card (which is a variable, as from time to time, it could be another NIC) and set this IP to the server_address option in my nrpe.cfg.

After some research, try and error, ansible_fact seems the way to gather those information. I think I will have to register a variable to use with my jinja2 template.

My main issue is how to retrieve IP address from named NIC (enp0s8).

Thanks for your advices.

Regards,

Nikos

Best Answer

If your playbook has gather_facts: yes or if you run a setup task in your playbook there should be a variable like this available.

- debug: 
    var: ansible_enp0s8.ipv4.address

If you want to see all the possible variables that are normally discovered run a command like this ansible some-hostname -m setup.

I try to build the following variable {{ ansible_{{ nrpe_address_server }}.ipv4.address }} it does not work

You don't use {{}} inside an expression, or to say it differently you can't nest them.

What you probably need is something like this.

- debug: 
    var: vars['ansible_'~nrpe_address_server].ipv4.address

Using the [] syntax allows you access specific variable using dynamic data. The ~ is concatenates strings.