简体   繁体   中英

Ansible: Extract first three octects from an IP address

I have a string with IP addr: 192.168.10.2

I want to extract first three octets of the IP in Ansible and I tried to use this regex.

{{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. It is better to match the whole ip and end your regex with $ , and also change //1 to \\\\1 in your code.

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

---
- 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') }}"

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