Created
December 20, 2018 11:19
-
-
Save mpneuried/76901e1c9b5e5531d59adefb35d0f404 to your computer and use it in GitHub Desktop.
AWS EC2 Security Groups: Revoke old and add new current ip to a list of rules based ob the description
This file contains 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/sh | |
# This script will update your ec2 security group with the current ip of your connection. | |
# To find the "old" rules the description is used | |
# Requirements: | |
# - aws-cli with configured profile: https://aws.amazon.com/de/cli/ | |
# - jq: https://stedolan.github.io/jq/ | |
# - curl | |
#################### | |
# CONFIGURATION | |
#################### | |
# This description willbe added to the new rules an d used to find and remove existing rules | |
DESC="{ replace this description }" | |
# the aws cli profile used | |
AWS_PROFILE="{ aws profile to use }" | |
# the aws ecs security group id to update the rules | |
GROUP_ID="{ use your group id }" | |
# A List of rules to update. The format is "{tcp|udp}:{port}". | |
declare -a RULES=( "tcp:443" "tcp:22" "udp:666" ) | |
# The url/service to get your currnet public ip | |
GET_IP_URL="https://api.ipify.org" | |
#################### | |
# SCRIPT | |
#################### | |
printf "get current ip ..." | |
NEW_IP=`curl -s $GET_IP_URL` | |
echo " $NEW_IP\n" | |
# add ip mask | |
NEW_IP+="/32" | |
printf "get ec2 sec. group '$GROUP_ID' ip ..." | |
SEC_GROUPS=`aws --profile $AWS_PROFILE ec2 describe-security-groups --group-id $GROUP_ID` | |
LAST_IP=`echo "$SEC_GROUPS" | jq --arg desc "$DESC" '.SecurityGroups[0].IpPermissions[].IpRanges[] | select( .Description == $desc ) | .CidrIp' -r | tail -1` | |
echo " $LAST_IP\n" | |
if [ -z $LAST_IP ] | |
then | |
echo "No matching rules found.\n" | |
elif [ $NEW_IP != $LAST_IP ] | |
then | |
echo "IP changed so change security group from '$LAST_IP' to '$NEW_IP'\n" | |
echo "revoke rule: old ingress rules" | |
for rule_revoke in "${RULES[@]}" | |
do | |
IFS=':' read -ra arr <<< "$rule_revoke" | |
echo "revoke protocol: ${arr[0]} port: ${arr[1]}" | |
aws --profile $AWS_PROFILE ec2 revoke-security-group-ingress --group-id $GROUP_ID --protocol ${arr[0]} --port ${arr[1]} --cidr $LAST_IP | |
done | |
else | |
echo "IP '$LAST_IP' not changed" | |
exit 1 | |
fi | |
echo "Add rules to security group." | |
for rule_authorize in "${RULES[@]}" | |
do | |
IFS=':' read -ra ara <<< "$rule_authorize" | |
echo "authorize rule: protocol: ${ara[0]} port: ${ara[1]}" | |
aws --profile $AWS_PROFILE ec2 authorize-security-group-ingress --group-id $GROUP_ID --ip-permissions IpProtocol=${ara[0]},FromPort=${ara[1]},ToPort=${ara[1]},IpRanges="[{CidrIp=\"$NEW_IP\",Description=\"$DESC\"}]" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment