Gana Sagar Gana Sagar - 4 months ago 47
Python Question

Regular expression matching for IP range in Ansible Playbooks for grouping

I am trying to write a regular expression for a dynamic group in ansible-playbook for an sample ip range.
if the address range is 172.30.0.(0 to 254).(0 to 254). My regex is like
172.30.[0-254].[0-254]. Is this correct ? Even though I have the hosts in the range, the tasks are being skipped and no groups are being formed.

tasks:
- group_by: key=adda
when: ansible_default_ipv4.network == '172.30.[0-254].[0-254]'

grouping picture

Answer

When using the operator '==' then in python you are trying to find a matched string with the name '172.30.[0-254[.[0-254]'

In ansible you can use python expression like search or match.

So you need to type something like this:

when: ansible_default_ipv4.address | match("172.30.")

Did a test ansible playbook to verify it.

Comments