Every so often I need to open up access to an AWS service to my home IP address. Unfortunately, my IP address is liable to change when my broadband router reconnects, so I wanted to automate the process of adding my local IP to the AWS security group. I created the following shell script to do this. It will retrieve your externally presenting IP address, and then add a new rule to the security group opening inbound connections to the specified port range. If the script has been run previously, the script will first delete the previously added rule.
#!/bin/bash
# Modify the following variables
GROUP_ID=sg-XXXXXXXXXXXX
PORT_FROM=5432
PORT_TO=5432
CACHED_RULE_ID_FILE=~/tmp/sg_ingress_id_1.txt
RULE_DESC=MyHomeIPIngress
IP=$(curl -s http://whatismyip.akamai.com/)
if ! echo "$IP" | grep -E -q "^([0-9]{1,3}\.){3}[0-9]{1,3}$"; then
echo "Invalid IP address ${IP}"
exit 1
fi
if [ -f "${CACHED_RULE_ID_FILE}" ]; then
aws ec2 revoke-security-group-ingress --group-id ${GROUP_ID} --security-group-rule-ids "$(cat ${CACHED_RULE_ID_FILE})"
fi
aws ec2 authorize-security-group-ingress --group-id ${GROUP_ID} --ip-permissions "IpProtocol=tcp,FromPort=${PORT_FROM},ToPort=${PORT_TO},IpRanges=[{CidrIp=${IP}/32,Description=${RULE_DESC}}]" | jq '.SecurityGroupRules[0].SecurityGroupRuleId' -r > "${CACHED_RULE_ID_FILE}"