简体   繁体   中英

Ansible & Vagrant: Get private network ip address

I'm trying to create a simple script to provision the machines in my Vagrant setup.

I currently have a private network set up, where each node in the Vagrant file has something like:

node.vm.network "private_network", ip: "172.16.xx"

And in my Ansible script, I originally used {{ ansible_eth2.ipv4.address }} to pick up the ip address in my playbook tasks.

When I recently swapped machines however, the Ansible variable was undefined because the new machine doesn't have a eth2 network interface. On the new machine, the private ip address set in the Vagrant file appears to be assigned to the eth1 interface.

In an attempt to get around this issue and make my Ansible playbooks hardware agnostic, I replaced all my references to {{ ansible_eth2.ipv4.address }} with {{ ansible_default_ipv4.address }} , but that retrieves the ip address at eth0 (10.0.xx in my case).

How can I set either the Vagrant file to always add the ip address to whatever network interface Ansible will use for {{ ansible_default_ipv4.address }} ?

Or failing that, is there anything I can do with Ansible (or even raw shellscript), to retrieve the private ip address?

At least one way, as there are likely several:

  - debug:
      verbosity: 0
      msg: |
          {%- for nic in ansible_interfaces -%}
          {%- for addr in (vars["ansible_"+nic]["ipv4"] | map(attribute="address") | list)
              if not (addr | regex_search('10(\.\d+){3}')) -%}
          nic {{ nic }} := {{ addr }}
          {%- endfor -%}
          {%- endfor -%}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM