Skip to content

Commit

Permalink
readd ip-allocation-threshold
Browse files Browse the repository at this point in the history
  • Loading branch information
Gianncarlo Giannattasio committed Mar 12, 2024
1 parent 2341eb5 commit 4d62749
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions c7n/resources/vpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2885,3 +2885,59 @@ def process(self, resources, event=None):
results.append(resource)

return results

@Subnet.filter_registry.register('ip-allocation-threshold')
class SubnetIpAllocationFilter(Filter):
"""Filters subnets based on ip allocation percentage
:example:
.. code-block:: yaml
policies:
- name: subnet-ip-threshold-policy
resource: subnet
filters:
- type: ip-allocation-threshold
percentage: 80
op: gte
"""
schema = type_schema(
'ip-allocation-threshold',
percentage={'type': 'number'},
op={'enum': ['eq', 'ne', 'lt', 'gt', 'lte', 'gte']}
)

permissions = ("ec2:DescribeSubnets",)

def calculate_ip_allocation(self, subnet):
subnetMask = subnet.get('CidrBlock').split('/')[1]
hostBits = 32 - int(subnetMask)
totalHost = ((2 ** hostBits) - 2)
availableHost = subnet.get('AvailableIpAddressCount')
ipsUsed = totalHost - availableHost
percentageOfIpsUsed = (ipsUsed / totalHost) * 100
return percentageOfIpsUsed

def process(self, resources, event=None):
results = []
threshold_percentage = self.data.get('percentage')
op = self.data.get('op')
for subnet in resources:
percentage_used = self.calculate_ip_allocation(subnet)
if op == 'eq':
if threshold_percentage == percentage_used:
results.append(subnet)
elif op == 'ne':
if threshold_percentage != percentage_used:
results.append(subnet)
elif op == 'lt':
if percentage_used < threshold_percentage:
results.append(subnet)
elif op == 'gt':
if percentage_used > threshold_percentage:
results.append(subnet)
elif op == 'lte':
if (percentage_used < threshold_percentage) or (percentage_used == threshold_percentage):
results.append(subnet)
elif op == 'gte':
if (percentage_used > threshold_percentage) or (percentage_used == threshold_percentage):
results.append(subnet)
return results

0 comments on commit 4d62749

Please sign in to comment.