Skip to content

Instantly share code, notes, and snippets.

@ankitdbst
Last active June 24, 2021 03:11
Show Gist options
  • Save ankitdbst/9bb9d2a8078286da4b13b674e1934e6a to your computer and use it in GitHub Desktop.
Save ankitdbst/9bb9d2a8078286da4b13b674e1934e6a to your computer and use it in GitHub Desktop.
Add current IP to Security Group in AWS using a description & port as filter
#!/bin/bash
while [[ "$#" -gt 0 ]]; do
case $1 in
-g|--group) group="$2"; shift ;;
-d|--description) description="$2"; shift;;
-p|--port) port="$2"; shift;;
-i|--ip) ip="$2"; shift;;
-f|--force) force=1;;
-h|--help) help=1;;
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
if [ -n "$help" ]; then
echo "usage: ./update-ip.sh -g <group-name> -d <description> [-p <port>] [-i <ip>]";
echo "use -f to force, if the rule is not present"
exit;
fi
if [ -z "$port" ]; then
port=22;
fi
# Remove existing rules
echo "Trying to remove rules with description '${description}' port ${port} from ${group}...";
cidr=$(aws ec2 describe-security-groups --group-name ${group} \
| jq -r ".SecurityGroups[] | .IpPermissions[] | select(.FromPort == ${port}) | .IpRanges[] | select(.Description == \"${description}\") | .CidrIp");
if [ -z "$cidr" ] && [ -z "$force" ]; then
echo "No CIDR block found for ${description} port ${port}";
exit;
fi
if [ -n "$cidr" ]; then
echo "Removing previous CIDR: ${cidr} for ${description} port ${port} in ${group}";
status=$(aws ec2 revoke-security-group-ingress \
--group-name ${group} \
--port ${port} \
--protocol tcp \
--cidr ${cidr} | jq -r ".Return");
# check if successful
if [ "${status}" != "true" ]; then
echo "Could not remove CIDR from ${group}";
exit;
fi
fi
# Add new rule with current IP
if [ -z "$ip" ]; then
ip=$(curl -s4 v4.ifconfig.co);
fi
echo "Adding current IP: $ip for port $port to $group with description $description...";
aws ec2 authorize-security-group-ingress \
--group-name ${group} \
--ip-permissions IpProtocol=tcp,FromPort=${port},ToPort=${port},IpRanges="[{CidrIp=${ip}/32,Description=\"${description}\"}]"
echo "Done!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment