简体   繁体   中英

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 xxx15 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.

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 you will need to use an external service to get it since your server may behind a NAT. ,则需要使用外部服务来获取它,因为您的服务器可能位于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] }}

As mentioned by jarv this can be obtained by using facts .

This can be done in the following ways:

For a list of all ipv4 addresses:

{{ ansible_all_ipv4_addresses }}

For the default ipv4 address:

{{ ansible_default_ipv4.address }}

If you know the ip address is on the eth0 interface:

{{ ansible_eth0.ipv4.address }} 

You can then append the .split('.')[3] method to the variable to get the appropriate output, for example {{ ansible_default_ipv4.address.split('.')[3] }}

This is an similar way to get it:

- name: Get the local IP
  local_action:
      module: uri
      url: http://checkip.amazonaws.com/
      return_content: yes
  register: ip_lookup
- set_fact:
      local_ip: "{{ ip_lookup.content | regex_replace('\n','') }}"
- debug: var=local_ip

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