Skip to content

Instantly share code, notes, and snippets.

@basimhennawi
Created August 30, 2021 11:16
Show Gist options
  • Save basimhennawi/42554cde17e29665ee947c4b1e41e5b6 to your computer and use it in GitHub Desktop.
Save basimhennawi/42554cde17e29665ee947c4b1e41e5b6 to your computer and use it in GitHub Desktop.
Bash Script to update an Existing AWS Security Group with my New Public IP Address using AWS CLI
#!/bin/bash
group_id="sg-12345678";
port="27017";
# Get existing IP rules for group matching port
ips=$(aws ec2 describe-security-groups --filters Name=ip-permission.to-port,Values=$port Name=ip-permission.from-port,Values=$port Name=ip-permission.protocol,Values=tcp --group-ids $group_id --output text --query 'SecurityGroups[*].{IP:IpPermissions[?ToPort==`'$port'`].IpRanges}' | sed 's/IP //g');
# Loop through IPs
for ip in $ips
do
# Delete IP rules matching port
aws ec2 revoke-security-group-ingress --group-id $group_id --protocol tcp --port $port --cidr $ip --region=eu-central-1
done
# Get my current IP
curl v4.ifconfig.co > ip.txt
awk '{ print $0 "/32" }' < ip.txt > fullip.txt
export mynewipaddress=$(cat fullip.txt)
# Add new rule to the SG with this specific IP
aws ec2 authorize-security-group-ingress --region=eu-central-1 \
--group-id $group_id \
--ip-permissions IpProtocol=tcp,FromPort=$port,ToPort=$port,IpRanges="[{CidrIp=${mynewipaddress},Description='tmp new'}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment