Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Bash Script to update an Existing AWS Security Group with my New Public IP Address using AWS CLI
# Get existing IP rules for group matching port
ips=$(aws ec2 describe-security-groups --filters,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
# 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
# Get my current IP
curl > 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