Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 10.10.10.15. 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 }}"

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

Edit:

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 

And

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

For using it later in the playbook.

like image 934
plamer Avatar asked Aug 20 '14 17:08

plamer


People also ask

How do you mention hosts in Ansible?

Devices or hosts are referenced by their DNS name or with the ansible inventory ip address variable. Hosts can be defined either by IP address or DNS name or if DNS is not resolvable using the ansible_host command. Multiple servers or network devices can be referenced in a playbook by referencing the group name.

How do I control Ansible playbook only on specific hosts?

Using the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.


1 Answers

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- 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:

{{ host_ip.stdout.split('.')[3] }}
like image 141
jarv Avatar answered Oct 27 '22 04:10

jarv