Last active
January 3, 2016 11:29
-
-
Save realguess/8456976 to your computer and use it in GitHub Desktop.
Authorize or revoke the public IP address of the current machine on all AWS security groups.
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
#!/usr/bin/env bash | |
# | |
# Authorize or revoke the public IP address of the current machine on all AWS | |
# security groups. | |
# | |
# Usage: | |
# | |
# # Authorize TCP port 22 access on all security groups: | |
# aws-security-group authorize 22 us-east-1 | |
# | |
# # Revoke TCP port 22 access on all security groups: | |
# aws-security-group revoke 22 us-east-1 127.0.0.1 | |
# | |
# TODO: Next step is to add security groups from all AWS regions. | |
# | |
# > (c) 2014 Chao Huang <chao@realguess.net> | |
if [ $# -lt 3 ]; then | |
echo "Usage: aws-security-group [authorize|revoke] [port] [region] [ip]" | |
exit 1 | |
fi | |
command=$1 | |
port=$2 | |
region=$3 | |
ip=$4 | |
protocol=tcp | |
# Define a simple structured log function. | |
function log { | |
echo -n "$(date) [$1] $2" | |
} | |
# Authorize an IP address. | |
function authorize { | |
aws ec2 authorize-security-group-ingress \ | |
--region $region \ | |
--output text \ | |
--group-id $1 \ | |
--protocol $protocol \ | |
--port $port \ | |
--cidr $ip/32 | |
} | |
# Revoke an IP address. | |
function revoke { | |
aws ec2 revoke-security-group-ingress \ | |
--region $region \ | |
--output text \ | |
--group-id $1 \ | |
--protocol $protocol \ | |
--port $port \ | |
--cidr $ip/32 | |
} | |
# Get public IP address of the machine. | |
if [ -z $ip ]; then | |
ip=$(curl -s ipinfo.io/ip) | |
log 'ipinfo.io' "Your public IP is $ip"; echo | |
fi | |
# Get all security group IDs. | |
ids=$(aws ec2 describe-security-groups \ | |
--region $region \ | |
--query 'SecurityGroups[*].GroupId' \ | |
--output text | awk '{ for (id = 1; id <= NF; id++) print $id }') | |
# Update each security group. | |
for id in $ids; do | |
if [ $command == 'authorize' ]; then | |
log 'aws' "Authorizing $id... " | |
authorize $id | |
else | |
log 'aws' "Revoking $id... " | |
revoke $id | |
fi | |
done | |
# Verify result by `aws ec2 describe-security-groups --group-names [mygroup]` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment