Created
May 19, 2021 14:37
-
-
Save leotada/4a59bc812c992e41d973e6e1809a2fa7 to your computer and use it in GitHub Desktop.
Add permission to own public IP on AWS EC2 SecurityGroup
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 python3 | |
from urllib.request import urlopen | |
import boto3 | |
class SecurityGroup: | |
def __init__(self, security_group_id: str): | |
ec2 = boto3.resource('ec2') | |
self.security_group_id = security_group_id | |
self.security_group = ec2.SecurityGroup(security_group_id) | |
def get_my_public_ip(self) -> str: | |
response = urlopen('https://api.ipify.org') | |
return response.read().decode() | |
def authorize_my_ingress(self, name: str): | |
response = self.security_group.authorize_ingress( | |
GroupId=self.security_group_id, | |
IpPermissions=[ | |
{ | |
'FromPort': 5432, | |
'ToPort': 5432, | |
'IpProtocol': 'tcp', | |
'IpRanges': [ | |
{ | |
'CidrIp': '{}/32'.format(self.get_my_public_ip()), | |
'Description': name | |
}, | |
], | |
} | |
] | |
) | |
return response | |
def revoke_my_ingress(self, name: str): | |
response = self.security_group.revoke_ingress( | |
GroupId=self.security_group_id, | |
IpPermissions=[ | |
{ | |
'FromPort': 5432, | |
'ToPort': 5432, | |
'IpProtocol': 'tcp', | |
'IpRanges': [ | |
{ | |
'CidrIp': '{}/32'.format(self.get_my_public_ip()), | |
'Description': name | |
}, | |
], | |
} | |
] | |
) | |
return response | |
if __name__ == '__main__': | |
rule_name = 'rule-description' | |
security_group = SecurityGroup('sg-id') | |
response1 = security_group.revoke_my_ingress(rule_name) | |
response2 = security_group.authorize_my_ingress(rule_name) | |
print(response1) | |
print(response2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment