How do you change ansible_default_ipv4?

这一生的挚爱 提交于 2019-12-20 18:42:32

问题


I'd like to change ansible_default_ipv4 to point to eth1 instead of eth0. Can I do this in either the playbook or via the --extra-vars option?


回答1:


ansible uses command ip -4 route get 8.8.8.8 to get the default ipv4 interface. You can change your ip/routing tables to make eth1 the default route and it'll return it.

Or you can use a custom fact.

PS: using set_fact to override the ansible_default_ipv4 fact, but it has it's own pitfalls due to caching, scope, ...




回答2:


Another option is always reference your interface explicitly. Different cloud providers have different conventions weather to put the private (usually 10.x.y.z) management network on eth0 or eth1.

Instead of referencing

ansible_default_ipv4["address"]

You can always define the iface you want (say in group_vars/all)

iface: eth0

and reference it in tasks as

{{ 'ansible_'+iface['ipv4']['address'] }}

A simple grep will show you all references. A global find and replace on your project will let you change this. grep -RH ansible_default_ipv4 .

Then when you want to switch cloud providers you simply adapt the iface as needed.

If you prefer something less verbose, and more explicit define

private_iface: eth0  #switch eth0,eth1 depending on your provider.
public_iface: eth1
private_host_ipv4: "{{ 'ansible_'+private_iface['ipv4']['address'] }}"
public_host_ipv4: "{{ 'ansible_'+public_iface['ipv4']['address'] }}"

and only use

ansible_default_ipv4

when you want to refer to either private or public ip that would be used to get to 8.8.8.8 (the internet in general).

BTW, i tried Eron Wright's suggestion for route add -net 8.8.8.8 netmask 255.255.255.255 eth1. It didn't seem to work for me, and i was unable to ping google (though pinging any other public ip worked).




回答3:


ip -4 route get 8.8.8.8 was not working on my server.

I created this work around.

- name: find default ipv4... this is a bit of a hack. shell: ifconfig $(route | grep default | awk '{print $(NF)}') | grep 'inet' | awk '{ print $2}' register: ipv4_address

Now I can use ipv4_address wherever needed!



来源:https://stackoverflow.com/questions/29495704/how-do-you-change-ansible-default-ipv4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!