Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed ansible.utils.ipaddr('host/prefix') function if size of subnet is 1 #373

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
9 changes: 9 additions & 0 deletions plugins/plugin_utils/base/ipaddr_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ def _ip_query(v):


def _address_prefix_query(v):
# Handle single IP address case
if v.size == 1:
# For IPv4, return False for a single IP without a /32 prefix
if v.version == 4 and v.prefixlen != 32:
return False
# For IPv6, return False for a single IP without a /128 prefix
if v.version == 6 and v.prefixlen != 128:
return False

if v.size > 2 and v.ip in (v.network, v.broadcast):
return False
return str(v.ip) + "/" + str(v.prefixlen)
Expand Down
16 changes: 16 additions & 0 deletions tests/unit/plugins/filter/test_ipaddr.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,22 @@ def test_range_usable(self):
self.assertEqual(ipaddr(address, "range_usable"), "1.12.1.1-1.12.1.254")

def test_address_prefix(self):
# Single IP address without a prefix, should return empty
address = "203.0.113.23"
self.assertFalse(ipaddr(address, "address/prefix"))

# Single IP address with /32, should return address with /32
address_with_prefix = "203.0.113.23/32"
self.assertEqual(ipaddr(address_with_prefix, "address/prefix"), address_with_prefix)

# Valid /24 network range, should return the address and prefix
network_address = "203.0.113.0/24"
self.assertEqual(ipaddr(network_address, "address/prefix"), network_address)

# Broadcast address of /24, should return False
broadcast_address = "203.0.113.255/24"
self.assertFalse(ipaddr(broadcast_address, "address/prefix"))

# Regular address
address = "1.12.1.12/24"
self.assertEqual(ipaddr(address, "address/prefix"), address)
Expand Down
Loading