Skip to content

Instantly share code, notes, and snippets.

@ajbrown
Last active March 19, 2021 07:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajbrown/6773c983052b109bc9529729ae280498 to your computer and use it in GitHub Desktop.
Save ajbrown/6773c983052b109bc9529729ae280498 to your computer and use it in GitHub Desktop.
Update a set of security groups, allowing SSH access from your current public IP address.
#!/usr/bin/env bash
#
# Add the security groups you want to allow the current IP address
# SSH access to by updating the "groups" array below. The user
# running the script must have the aws-cli installed and configured.
# Their credentials will be used for API calls, so access should be
# controlled that way.
#
# Note: It's a good idea to clean up these security groups regularly.
# I prefer to have a security group that I can remove all ingress rules
# At any time, and force everyone to re-run this script when they lose
# access.
#
declare -a groups=( "sg-eef7e796" "sg-1375d275" )
ip=`curl 'https://api.ipify.org'`
hadErrors=0
echo "Your IP is ${ip}. Adding you to the security groups."
for g in "${groups[@]}"; do
cmd="aws ec2 authorize-security-group-ingress --group-id ${g} --protocol tcp --port 22 --cidr ${ip}/32"
error=$( $cmd 2>&1 )
if [[ $error == *"InvalidPermission.Duplicate"* ]]; then
echo "IP already exists.";
elif [ "$error" != "" ]; then
echo "There was an error adding your IP: ${error}"
hadErrors=1
fi
done
echo "All done."
if [ "$hadErrors" == "1" ]; then
echo "There were some errors, so you you may not have access."
fi
@jdbrown66
Copy link

Tried out the script now that I have aws cli installed and configured. Very handy.

One minor thing, though, -ne is typically an arithmetic operator so when I would run the script it would complain about line 28

./letmein.sh: line 28: [: : integer expression expected

Changing the operator from -ne to != seems to do the trick.

@ajbrown
Copy link
Author

ajbrown commented Aug 23, 2016

@jdbrown66 Updated, thanks for the suggestion

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