简体   繁体   English

Ansible IP地址变量 - 主机部分

[英]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. 我在Ansible的命令行上编写用于设置IP地址的playbook。 Lets say 10.10.10.x. 让我们说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. 我需要获取我的公共IP的最后一部分,然后说xxx15并将其分配给私有: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. {{ var }}应该是公共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. 您可以使用ansible 事实代替使用系统实用程序,但您会发现接口名称因服务器而异。

You specifically mentioned the last part of my public IP 您特别提到了我公共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. 如果您的确意味着您的公共IP ,则需要使用外部服务来获取它,因为您的服务器可能位于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: 这将给你的公共IP,接下来得到你可以做的最后一个八位字节:

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

As mentioned by jarv this can be obtained by using facts . 正如jarv所提到的,这可以通过使用事实来获得。

This can be done in the following ways: 这可以通过以下方式完成:

For a list of all ipv4 addresses: 有关所有ipv4地址的列表:

{{ ansible_all_ipv4_addresses }}

For the default ipv4 address: 对于默认的ipv4地址:

{{ ansible_default_ipv4.address }}

If you know the ip address is on the eth0 interface: 如果你知道ip地址在eth0接口上:

{{ 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] }} 然后,您可以将.split('.')[3]方法附加到变量以获取适当的输出,例如{{ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM