Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discover management IP and use it in a template

I'm trying to setup my sshd_config file using Ansible. For design reasons (we have both virtual and physical machines, with different NICs) the management interface is not fixed, so in my template I cannot just put

{{ ansible_eth0.ipv4.address }}

because I don't know in advance which interface is going to be management interface so, I need discovering it. I know the IP is always going to be inside a range (e.g. 192.168.1.0/24).

How can I discover which interface has that IP and then use it in the template?

like image 726
Ignacio Verona Avatar asked Dec 14 '22 20:12

Ignacio Verona


1 Answers

Ansible provides a fact named ansible_all_ipv4_addresses that is a list of all ip addresses.

To find the management IP see this working example:

test.yml:

- hosts: all
  gather_facts: yes
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - set_fact:
        man_ip: "{{ item }}"
      with_items: "{{ ansible_all_ipv4_addresses }}"
      when: "item.startswith('192.168.1')"
    - debug: var=man_ip
  • set_fact registers a variable that can be used later in your play
  • with_items iterates over all ip addresses
  • when: "item.startswith('192.168.1')" will limit the assignment to ips that start with 192.168.1

Run the test play locally:

ansible-playbook -c local -i localhost, test.yml

The variable {{ man_ip }} will have the ip address of the management ip address.

like image 200
jarv Avatar answered Jan 06 '23 10:01

jarv