Skip to content

Instantly share code, notes, and snippets.

@jonathanhle
Last active September 13, 2023 00:05
Show Gist options
  • Save jonathanhle/a7fa989d5dedbcde4729e405c5754de3 to your computer and use it in GitHub Desktop.
Save jonathanhle/a7fa989d5dedbcde4729e405c5754de3 to your computer and use it in GitHub Desktop.
Quick loop through SGs to update them with a new CIDR, if there's an existing one. Only dealing with untagged SGs that are probably ClickOps
import boto3
# Initialize boto3 client
ec2 = boto3.client('ec2')
# CIDRs to check
EXISTING_CIDRS = ["1.2.3.4/32", "5.6.7.8/32"]
NEW_CIDR = '10.11.12.13/22'
# Create a paginator for the describe_security_groups method
paginator = ec2.get_paginator('describe_security_groups')
# Call the paginator in a loop
for page in paginator.paginate():
for sg in page['SecurityGroups']:
# Check if the security group already contains the NEW_CIDR
if any(
ip_range.get('CidrIp') == NEW_CIDR
for permission in sg['IpPermissions']
for ip_range in permission.get('IpRanges', [])
):
print(
f"Skipping security group {sg['GroupId']} as it already contains CIDR {NEW_CIDR}.")
continue
# Filter security groups with no tags
if 'Tags' not in sg or not sg['Tags']:
# Iterate through the ingress rules of the security group
for permission in sg['IpPermissions']:
for ip_range in permission.get('IpRanges', []):
if ip_range['CidrIp'] in EXISTING_CIDRS:
protocol = permission['IpProtocol']
from_port = permission.get('FromPort', None)
to_port = permission.get('ToPort', None)
print(
f"Found CIDR {ip_range['CidrIp']} in security group {sg['GroupId']} "
f"for protocol {protocol} on ports {from_port if from_port else 'ALL'}-{to_port if to_port else 'ALL'}."
)
try:
args = {
'GroupId': sg['GroupId'],
'IpProtocol': protocol,
'CidrIp': NEW_CIDR
}
if from_port and to_port:
args['FromPort'] = from_port
args['ToPort'] = to_port
ec2.authorize_security_group_ingress(**args)
print(
f"Successfully added ingress rule to {sg['GroupId']} for CIDR {NEW_CIDR}.")
except Exception as e:
print(
f"Error adding ingress rule to {sg['GroupId']}: {e}")
print("Script completed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment