Update Your AWS Security Group Using Python & boto3
Tags: aws, cloud, howto, scripting
Published: 2022-08-31 00:51:38

---
title: Update Your AWS Security Group Using Python & boto3
published: true
date: 2022-07-20 19:23:00 UTC
tags: aws,cloud,HowTo,Scripting
canonical_url: https://ducko.uk/update-aws-security-group-using-python-boto3/
---

# Why?
 ![Update Your AWS Security Group Using Python & boto3](https://cdn.getmidnight.com/4058eed71b1f8e44d86c20a5090a5a21/2022/08/philipp-katzenberger-iIJrUoeRoCQ-unsplash.webp)

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.

![Update Your AWS Security Group Using Python & boto3](https://cdn.getmidnight.com/4058eed71b1f8e44d86c20a5090a5a21/2022/08/python-script-run.webp)
_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](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()
```

The script will require changes on Line 18 and Li to work with your security group. Please be aware of the difference between Security Group ID and Security Group Rule ID.

- Line 18 – Replace SGR-12345789abc with the Security Group Rule ID you want to amend.
- You can find this rule ID in the AWS console by browsing your security groups, selecting the SG you want to be able to amend and finding the rule containing your TCP 22 SSH Inbound. Next to it, you'll locate your Rule ID.

![Update Your AWS Security Group Using Python & boto3](https://cdn.getmidnight.com/4058eed71b1f8e44d86c20a5090a5a21/2022/08/sec-group-console.webp)
_Security group rule ID in the AWS console._

- Line 30 – Replace sg-12345789abc with the Security Group ID, found again in your AWS console by browsing your security groups.

You will need pip's relevant packages/ modules to run the script (depending on your version).  

```
pip install urllib requests boto3
or
pip3 install urllib requests boto3
```

Also, ensure you have your AWS CLI credentials set up. You can follow the [instructions here](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html) to quickly set this up.

All that's left to do is run the script! (depending on your version)

```
python sg-updates.py
or
python3 sg-updates.py
```