Question:
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: 10.10.10.15. Is there a variable for this? Can i capture some? I’ve tried to use something like:
1 2 3 |
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:
1 2 |
"shell: /dir/script --options 10.10.10.{{ var }}" |
and {{ var }}
should be the host part of the public IP.
Edit:
Thank you! Here’s my final solution:
1 2 3 4 |
- name: Get the host part of the IP shell: host {{ ansible_fqdn }} | awk '{print $4}' register: host_ip |
And
1 2 |
{{ host_ip.stdout.split('.')[3] }} |
For using it later in the playbook.
Answer:
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
1 2 3 |
shell: wget -qO- http://ipecho.net/plain ; echo register: host_ip |
That will give your public IP, next to get the last octet you could do something like:
1 2 |
{{ host_ip.stdout.split('.')[3] }} |