Skip to content

Instantly share code, notes, and snippets.

Last active Mar 30, 2020
What would you like to do?
Update AWS Route 53 and EC2 Security Group upon change in dynamic IP address. Roll your own dynamic DNS service, and update associated security groups by adding the new IP and cleaning up the previous IP to prevent unauthorized access to EC2 instances. Note: calls AWS CLI, and cli53 to make Route 53 changes (
CURRENT_IP=$(dig +short)
OLD_IP=$(dig $HOSTNAME.$ZONE +short)
if [[ $CURRENT_IP =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]] ; then
if [[ $OLD_IP != $CURRENT_IP ]] ; then
# Update the DNS entry to reflect the new IP
cli53 rrcreate --replace $ZONE "$HOSTNAME 60 A $CURRENT_IP"
# Add the new IP to the Security Group
aws ec2 authorize-security-group-ingress --group-name $SGROUP --protocol tcp --port 22 --cidr $CURRENT_IP/32
aws ec2 authorize-security-group-ingress --group-name $SGROUP --protocol tcp --port 53 --cidr $CURRENT_IP/32
aws ec2 authorize-security-group-ingress --group-name $SGROUP --protocol udp --port 53 --cidr $CURRENT_IP/32
aws ec2 authorize-security-group-ingress --group-name $SGROUP --protocol tcp --port 80 --cidr $CURRENT_IP/32
# Remove the old IP from the Security Group
aws ec2 revoke-security-group-ingress --group-name $SGROUP --protocol tcp --port 22 --cidr $OLD_IP/32
aws ec2 revoke-security-group-ingress --group-name $SGROUP --protocol tcp --port 53 --cidr $OLD_IP/32
aws ec2 revoke-security-group-ingress --group-name $SGROUP --protocol udp --port 53 --cidr $OLD_IP/32
aws ec2 revoke-security-group-ingress --group-name $SGROUP --protocol tcp --port 80 --cidr $OLD_IP/32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment