Skip to content

Instantly share code, notes, and snippets.

@dgulinobw
Created July 22, 2021 18:12
Show Gist options
  • Save dgulinobw/3818ae3ed9b328dc9435de8221e2ec55 to your computer and use it in GitHub Desktop.
Save dgulinobw/3818ae3ed9b328dc9435de8221e2ec55 to your computer and use it in GitHub Desktop.
Search and replace an IP/CIDR in all AWS EC2 security groups
#!/usr/bin/env python
from __future__ import print_function
import json
import boto3
from botocore.exceptions import ClientError
ip="50.56.24.206/32"
new_ip="192.237.176.126/32"
for region in ["us-east-1","us-west-1", "us-west-2"]:
ec2=boto3.client('ec2', region )
sgs = ec2.describe_security_groups()["SecurityGroups"]
for sg in sgs:
group_name = sg["GroupName"]
for rule in sg["IpPermissions"]:
for range in rule["IpRanges"]:
try:
if range["CidrIp"] == ip:
to_port = rule['ToPort']
from_port = rule['FromPort']
protocol = rule['IpProtocol']
print("%s,%s, from_port: %s, to_port: %s" % (region, group_name, from_port, to_port))
ec2.revoke_security_group_ingress(
GroupId=sg["GroupId"],
IpPermissions = [{'IpRanges':[{'CidrIp': ip}], 'FromPort': from_port, 'ToPort': to_port, 'IpProtocol': protocol}]
)
try:
ec2.authorize_security_group_ingress(
GroupId=sg["GroupId"],
IpPermissions = [{'IpRanges':[{'CidrIp': new_ip}], 'FromPort': from_port, 'ToPort': to_port, 'IpProtocol': protocol}]
)
except:
pass
except:
print(rule)
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment