← Back to list

AWS — Update Security Groups Rule Automatically

The majority of us do not have static IP configured on our Router, which means it keeps getting updated dynamically (auto-assigned). So…

0ccupi3R · 2021-09-26 13:54 · 3 claps · 1.5 min read
#security #aws #securitygroup #bash #script
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud

AWS — Update Security Groups Rule Automatically

Photo by Fotis Fotopoulos [Unsplash]

Photo by Fotis Fotopoulos [Unsplash]

The majority of us do not have static IP configured on our Router, which means it keeps getting updated dynamically (auto-assigned). So, with a traditional approach to manually update Security Groups ingress rules is a time consuming process.

😲 Now what ? Why don’t we make it simple for us or even automate it !

Prerequisites:

  1. AWS Cli configured (with/without SSO). Generate the credentials (using Key-pairs / STS) and validate if it is saved in ~/.aws/credentials
  2. A Script, obviously

How to configure :

  1. Copy script in your system, say /opt/aws-sg-update.sh
  2. Replace home-router with your security group name, if possible, then use same security group name for mutiple AWS accounts.
  3. To configure it as a command, add an alias in ~/.bashrc
alias sg-update="sh /opt/aws-sg-update.sh"
  1. Then reload your profile using the command source ~/.bashrc
  2. Finally, you are good to go to execute your command
aws-sg-update.sh udp 53 dev

Note: dev is an AWS profile name (use if you have multiple accounts)

Commandline Output :

{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-01234567890123456",
            "GroupId": "sg-01234567890123456",
            "GroupOwnerId": "012345678901",
            "IsEgress": false,
            "IpProtocol": "udp",
            "FromPort": 53,
            "ToPort": 53,
            "CidrIpv4": "1.2.4.5/32"
        }
    ]
}

AWS Console Output :

Note: Few tweaks that can be done :

  • Adding more arguments in aws command
  • To automate, configure Cron job crontab -e for your script (with/without hardcoded parameters)
# This will run on every hour
0 * * * * /usr/bin/sh /opt/aws-sg-update.sh
OR
0 * * * * /usr/bin/sh /opt/aws-sg-update.sh all all
  • Add your slack/telegram webhook to get the message when SG gets updated

Code : https://github.com/0ccupi3R/automation-scripts/blob/main/aws-scripts/aws-sg-update.sh


메타데이터
post_id
71f69c5d7c76
slug
aws-update-security-groups-rule-automatically-71f69c5d7c76
url
https://medium.com/@0ccupi3R/aws-update-security-groups-rule-automatically-71f69c5d7c76
canonical_url
https://medium.com/@0ccupi3R/aws-update-security-groups-rule-automatically-71f69c5d7c76
author_url
https://medium.com/@0ccupi3R
status
ok
fetched_at
2026-06-16 19:09:56