plamer plamer - 1 year ago 308
Bash Question

Ansible IP address variable - host part

I have the following problem:

I'm writing playbook for setting IP address on the command line in Ansible. Lets say 10.10.10.x. I need to get the last part of my public IP lets say x.x.x.15 and assign it to the private: Is there a variable for this? Can i capture some? I've tried to use something like:

shell: "ip addr show | grep inet ...."
register: host_ip

But it is not what i need. It works, but only for a limited number of servers.

The whole thing should be like that:

"shell: /dir/script --options 10.10.10.{{ var }}"

{{ var }}
should be the host part of the public IP.


Thank you! Here's my final solution:

- name: Get the host part of the IP
shell: host {{ ansible_fqdn }} | awk '{print $4}'
register: host_ip


{{ host_ip.stdout.split('.')[3] }}

For using it later in the playbook.

Answer Source

Instead of using a system utility you can use ansible facts though you will find that interface names will vary from server to server.

You specifically mentioned the last part of my public IP

If you really mean your public IP you will need to use an external service to get it since your server may behind a NAT. Here is one option

shell: wget -qO- ; echo
register: host_ip

That will give your public IP, next to get the last octet you could do something like:

{{ host_ip.stdout.split('.')[3] }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download