Skip to content

Instantly share code, notes, and snippets.

@13Cubed
Last active March 30, 2020 09:43
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 13Cubed/6c6ef65d17be1cb322f9a261c2f2e038 to your computer and use it in GitHub Desktop.
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 (https://github.com/barnybug/cli53).
#!/bin/bash
ZONE="example.com"
HOSTNAME="test"
SGROUP="my_security_group"
CURRENT_IP=$(dig @resolver1.opendns.com myip.opendns.com +short)
OLD_IP=$(dig @resolver1.opendns.com $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
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment