[英]Ansible: Extract first three octects from an IP address
I have a string with IP addr: 192.168.10.2
我有一个带IP地址的字符串: 192.168.10.2
I want to extract first three octets of the IP in Ansible and I tried to use this regex. 我想在Ansible中提取IP的前三个八位字节,并尝试使用此正则表达式。
{{comp_ip | regex_replace("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"), "//1"}}
This does not yield any result. 这不会产生任何结果。 Can someone correct me where I went wrong? 有人可以纠正我哪里出错了吗?
如果已经有点分隔的IP地址,则有一种简单的方法:
{{ comp_ip.split('.')[0:3] | join('.') }}
You are doing it right, you just have to use parenthesis in Regex to make a group. 您做对了,只需要在Regex中使用括号即可组成一个组。 It is better to match the whole ip
and end your regex with $
, and also change //1
to \\\\1
in your code. 最好匹配整个ip
并用$
结束您的正则表达式,并在代码中将//1
更改为\\\\1
。
Change regex from: 将正则表达式从:
^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}
To this regex: 到此正则表达式:
^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\.[0-9]{1,3}$
This is the full code: 这是完整的代码:
{{comp_ip | regex_replace('^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\.[0-9]{1,3}$', '\\1')}}
In case you want to calculate your network address you can use Ansible ipaddr filter which provides exactly this functionality: http://docs.ansible.com/ansible/latest/playbooks_filters_ipaddr.html 如果要计算您的网络地址,可以使用Ansible ipaddr过滤器 ,该过滤器完全提供此功能: http ://docs.ansible.com/ansible/latest/playbooks_filters_ipaddr.html
---
- hosts: localhost
vars:
my_ip: "{{ ansible_default_ipv4.network }}/{{ ansible_default_ipv4.netmask }}"
tasks:
- debug: msg="network {{ my_ip | ipaddr('network') }}"
- debug: msg="netmask {{ my_ip | ipaddr('netmask') }}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.