Update Your AWS Security Group Using Python & boto3

Why? 

I'm regularly (once a week) having to update a security group for my EC2 instances to allow SSH access due to the nature of consumer home broadband. So your IP changes frequently if you haven't or have the ability to purchase a static IP.

I wanted to create a script that will save time clicking through, logging into AWS, finding your Security group, and amending the rule.

What was put together? 

A small (primitive) python script that will pull your current external IP, and amend the current rule ID located within a security group in AWS, feeds back the response code from AWS (200 = OK) and exits out.

Outcome? 

A quick, easy and painless way to update security groups when you find out you can't SSH to your instances.

Pasted image 20240917153740.png

The script runs and provides 200 response codes on completion.

Where is your script located? 

Find it here: https://github.com/dannyducko/AWS-SG-Update-Python.

How can I get it working for myself? 

The script is primitive, so apologies if it's messy/ basic.

from urllib import response
import requests
import boto3
from botocore.exceptions import ClientError

ec2 = boto3.client('ec2')
my_ip = ""

def myip():
    global my_ip
    ## call the api on my-ip.io
    url = "https://api.my-ip.io/ip"
    ip_response = requests.request("GET", url)
    my_ip = (ip_response.text + "/32")

def des_sg(ip):
    ## Replace the sgr with the security group rule containing your IP you SSH from.
    sg_rules_list = [{'SecurityGroupRuleId': 'sgr-123456789abc',
                  'SecurityGroupRule': {
                      'IpProtocol': 'tcp',
                      'FromPort': 22,
                      'ToPort': 22,
                      'CidrIpv4': f'{ip}',
                      'Description': 'Added SSH port via script'
                  }
                  }
                 ]
    try:
        ## replace the below with the security group ID that contains the SG Rule
        response = ec2.modify_security_group_rules(GroupId='sg-123456789abc', SecurityGroupRules=sg_rules_list)
        print(f"Response code = {response['ResponseMetadata']['HTTPStatusCode']}")
    except ClientError as e:
        print(e)

def run_sg_replace():
    myip()
    sg_question = input(f"Would you like to replace your SG Rule to {my_ip}? (y or n)\n... ")
    if sg_question == "y" or "Y":
        des_sg(my_ip)
        #print("Successfully added")
    else:
        print("Closing...")
        exit()

run_sg_replace()
exit()


Great! Next, complete checkout for full access to Art of Infra.
Welcome back! You've successfully signed in.
You've successfully subscribed to Art of Infra.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.