DEV Community

Danny Jones
Danny Jones

Posted on • Originally published at ducko.uk on

Update Your AWS Security Group Using Python & boto3

Why?

Update Your AWS Security Group Using Python & boto3

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
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()
Enter fullscreen mode Exit fullscreen mode

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
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
Enter fullscreen mode Exit fullscreen mode

Also, ensure you have your AWS CLI credentials set up. You can follow the instructions here 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)