4

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?

techraf
  • 64,883
  • 27
  • 193
  • 198
Ignacio Verona
  • 655
  • 2
  • 8
  • 22

2 Answers2

13

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.

Ian Gregory
  • 5,770
  • 1
  • 29
  • 42
jarv
  • 5,338
  • 24
  • 26
0

This is slightly tricky to run inside a role when you have gather_facts: false in your playbook.

However, you can run setup selectively inside a role like this.

---
- setup:
    gather_subset: [network]

- debug: msg={{ ansible_all_ipv4_addresses }}

See https://docs.ansible.com/ansible/latest/modules/setup_module.html

Ryan
  • 4,594
  • 1
  • 32
  • 35