Last active
June 23, 2019 15:34
-
-
Save 0xtf/76a1e008e655b49d5e8c4299d39df66a to your computer and use it in GitHub Desktop.
Update entries inside a AWS Security Group based on their description
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This is based on the work done at https://gist.github.com/isalgueiro/212a612fc232f1437ce88876937691d3/revisions#diff-c6d6f47361666bfba5538e6e0101bafd | |
#################### | |
# Define variables # | |
#################### | |
# Expected for securityGroupIds is sg-... | |
securityGroupIds="Insert_Your_SGID" | |
# Expected for ruleDescription is something like Home, or OfficeNY | |
ruleDescription="Insert_Your_RuleDescription" | |
# Expected for rulePort is the port number, like 22, or 443 | |
rulePort="22" | |
# Retrieve my public IP | |
publicIP=`dig +short myip.opendns.com @resolver1.opendns.com` | |
## Define cidrIP and describe rules that match the conditions | |
cidrIP=`aws ec2 describe-security-groups --group-ids $securityGroupIds | jq -r '.SecurityGroups[0].IpPermissions[] | select(.ToPort=='$rulePort') | .IpRanges[] | select(.Description == "'$ruleDescription'") | .CidrIp' | tail -1f` | |
## Run cidrIP and delete it if it finds something | |
if [ -n "${cidrIP}" ]; then | |
aws ec2 revoke-security-group-ingress --group-id $securityGroupIds --ip-permissions '[{"IpProtocol": "tcp", "FromPort": '$rulePort', "ToPort": '$rulePort', "IpRanges": [{"CidrIp":"'$cidrIP'"}]}]' | |
fi | |
## Add the new rule with the conditions that were set | |
aws ec2 authorize-security-group-ingress --group-id $securityGroupIds --ip-permissions '[{"IpProtocol": "tcp", "FromPort": '$rulePort', "ToPort": '$rulePort', "IpRanges": [{"CidrIp": "'$publicIP'/32", "Description": "'$ruleDescription'"}]}]' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment