Skip to content

Instantly share code, notes, and snippets.

@SamLR
Created July 12, 2019 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamLR/37da447f888daf2f8086abd9d98f4577 to your computer and use it in GitHub Desktop.
Save SamLR/37da447f888daf2f8086abd9d98f4577 to your computer and use it in GitHub Desktop.
Add a new CIDR to inbound connections for security groups that already permit another, specific, CIDR
#
# Find all the security groups that use a particular CIDR_TO_FIND and update
# them with a new ingress rule allowing access from CIDR on ports 0->65535
#
# DESCRIPTION can also be set to describe the new rule.
#
# If DRY_RUN is set to true the security groups will be searched for but not
# updated.
#
import boto3
from botocore.exceptions import ClientError
DRY_RUN=True
CIDR='SOME NEW IP/32'
DESCRIPTION='Back up VPN'
CIDR_TO_FIND='SOME OLD IP/32'
ERROR_SGS=[]
def get_all(client, func_name, results_key, **kwargs):
paginator = client.get_paginator(func_name)
res = []
for page in paginator.paginate(**kwargs):
res += page[results_key]
return res
def get_security_groups_with(client, ip):
filter = [{'Name': 'ip-permission.cidr', 'Values':[ip]}]
return get_all(client, 'describe_security_groups', 'SecurityGroups', Filters=filter)
def add_cidr(client, sgid, cidr, description='CIDR to allow'):
try:
client.authorize_security_group_ingress(
DryRun=DRY_RUN,
GroupId=sgid,
IpPermissions=[{
'IpRanges':[
{'CidrIp':cidr, 'Description': description}
],
'FromPort':0,
'ToPort':65535,
'IpProtocol':'tcp'
}
]
)
except ClientError as e:
print(e)
ERROR_SGS.append(sgid)
def main():
client = boto3.client('ec2')
to_update = get_security_groups_with(client, CIDR_TO_FIND)
for sg in to_update:
sgid = sg['GroupId']
print('Updating: ', sgid)
add_cidr(client, sgid, CIDR, description=DESCRIPTION)
print('\nFinished.')
if len(ERROR_SGS) > 0:
print('\n{} errors out of {} attempts.\nids={}'.format(len(ERROR_SGS), len(to_update), ERROR_SGS))
else:
print('\nUpdated {} security groups'.format(len(to_update)))
if __name__ == '__main__':
main()
@SamLR
Copy link
Author

SamLR commented Jul 12, 2019

Requires python3 & boto3

Assumes AWS credentials are already available in the environment

Effectives updates all security groups that have a rule that contains CIDR SOME OLD IP/32 to have a new rule allowing ingress from SOME NEW IP/32.

WARNING this makes no attempt to replicate the existing rule for the old ip (e.g. if the previous rule was to deny old ip this will still allow new Ip; if the previous rule was only allow port 22 UDP this will allow all TCP ports etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment