Last active
October 9, 2017 16:33
-
-
Save angrychimp/ca82fd0ccf981eb6e1b3ef456c7ce146 to your computer and use it in GitHub Desktop.
Script to refresh an AWS VPC security group with your local IP address
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 | |
SGID=sg-123ad456 | |
PROFILE=aws-profile | |
# Add current IP to ingress list | |
myip=$(curl -s https://rand.tools/ip/) | |
aws --profile $PROFILE ec2 authorize-security-group-ingress --dry-run --group-id $SGID --ip-permissions "[{\"IpProtocol\": \"tcp\", \"FromPort\": 22, \"ToPort\": 22, \"IpRanges\": [{\"CidrIp\": \"$myip/32\"}]}]" | |
# Remove any old IPs from ingress | |
OIFS=$IFS | |
IFS=$'\n' | |
for i in $(aws --profile $PROFILE ec2 describe-security-groups --group-id $SGID --query "SecurityGroups[*].IpPermissions[*].{IpProtocol:IpProtocol,ToPort:ToPort,FromPort:FromPort,Ips:IpRanges[*].CidrIp|join(\`,\`,@)}" --output text); do | |
IFS=$OIFS | |
items=($i) | |
for ip in $(echo ${items[2]} | sed -e 's/,/ /g'); do | |
if [[ $ip != "$myip/32" ]]; then | |
echo "REMOVE: $ip ${items[1]} ${items[0]} ${items[3]}" | |
aws --profile $PROFILE ec2 revoke-security-group-ingress --group-id $SGID --ip-permissions "[{\"IpProtocol\": \"${items[1]}\", \"FromPort\": ${items[0]}, \"ToPort\": ${items[3]}, \"IpRanges\": [{\"CidrIp\": \"$ip\"}]}]" | |
fi | |
done | |
IFS=$'\n' | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment