Created
February 20, 2018 18:35
-
-
Save dgulinobw/48a8f3c46176ae9fb9f9a8e477a528b3 to your computer and use it in GitHub Desktop.
Replaces CidrIP with new one in all AWS EC2 security groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import json | |
import boto3 | |
ip="1.1.1.1/32" | |
new_ip="2.2.2.2/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