Reputation: 97
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?
Upvotes: 3
Views: 9263
Reputation: 2315
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') }}"
Upvotes: 1
Reputation: 68339
If already have dot-separated IP-address, there is a simple way:
{{ comp_ip.split('.')[0:3] | join('.') }}
Upvotes: 12
Reputation: 6098
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')}}
Upvotes: 2