Skip to content

Instantly share code, notes, and snippets.

@isalgueiro
Forked from antonmry/updateAWSecurityGroup.bash
Last active December 15, 2020 16:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isalgueiro/212a612fc232f1437ce88876937691d3 to your computer and use it in GitHub Desktop.
Save isalgueiro/212a612fc232f1437ce88876937691d3 to your computer and use it in GitHub Desktop.
Simple bash script to update a Security Group matched by description and port in AWS with your Public IP
#! /bin/bash
publicIP=`dig +short myip.opendns.com @resolver1.opendns.com`
securityGroupIds="sg-stuffstuff"
ruleDescription="This is the string we're using to find our rule"
## Consult previous one
awsOutput=`aws ec2 describe-security-groups --group-ids $securityGroupIds`
ipRangeIndex=`echo $awsOutput | gron | grep $ruleDescription | sed "s/.\+IpRanges\[\([0-9]\+\)\].\+/\1/"`
cidrIP=`echo $awsOutput | gron | grep "IpRanges\[$ipRangeIndex\].CidrIp" | sed "s/.\+ \= \"\(.\+\)\";/\1/"`
## Delete the previous one
if [ -n "${cidrIP}" ]; then
aws ec2 revoke-security-group-ingress --group-id $securityGroupIds --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "IpRanges": [{"CidrIp":"'$cidrIP'"}]}]'
fi
## Add the new one
aws ec2 authorize-security-group-ingress --group-id $securityGroupIds --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "IpRanges": [{"CidrIp": "'$publicIP'/32", "Description": "'$ruleDescription'"}]}]'
@sunnikumar
Copy link

sunnikumar commented Apr 22, 2020

Can you please print sample output of these two lines
ipRangeIndex=echo $awsOutput | gron | grep $ruleDescription | sed "s/.\+IpRanges\[\([0-9]\+\)\].\+/\1/"
cidrIP=echo $awsOutput | gron | grep "IpRanges\[$ipRangeIndex\].CidrIp" | sed "s/.\+ \= \"\(.\+\)\";/\1/"
above scrip not able to revoke old Ip from security group

@isalgueiro
Copy link
Author

Nope, sorry. I'm not currently using this script as it only works if ruleDescription only appears in one time in the JSON returned by AWS, and that doesn't cover my use case right now.

@ivanshim
Copy link

do you have a version that works without gron ?

@isalgueiro
Copy link
Author

do you have a version that works without gron ?

No, this is the only version I have, sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment