Created
April 15, 2021 22:31
-
-
Save ronoaldo/b1e3e31e79ed64c07233c3537208f696 to your computer and use it in GitHub Desktop.
Update clouddns at boot/shutdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
### BEGIN INIT INFO | |
# Provides: boxdns | |
# Required-Start: $remote_fs $syslog | |
# Required-Stop: $remote_fs $syslog | |
# Default-Start: 2 3 4 5 | |
# Default-Stop: 0 1 6 | |
# Short-Description: Updates the DNS dynamically | |
# Description: Updates the DNS of the box dynamically | |
### END INIT INFO | |
metadata() { | |
curl --fail -s -H Metadata-Flavor:Google "http://metadata/computeMetadata/v1/instance/$1" | |
} | |
# Use Cloud DNS to update hostname | |
export DNS_ZONE="$(metadata 'attributes/clouddns-zone')" | |
export DNS_NAME="$(metadata 'attributes/clouddns-name')" | |
export DNS_PROJECT="$(metadata 'attributes/clouddns-project')" | |
export PUBLIC_IP=$(metadata 'network-interfaces/0/access-configs/0/external-ip') | |
replace_dns() { | |
TYPE="$1" | |
DATA="$2" | |
dns="gcloud dns --project=$DNS_PROJECT record-sets" | |
echo "Configuring cloud DNS with 60s TTL" | |
$dns transaction start -z $DNS_ZONE | |
$dns list -z $DNS_ZONE --name $DNS_NAME --format='value(name,type,ttl,rrdatas)' | while read name type ttl data ; do | |
$dns transaction remove -z $DNS_ZONE --name=$name --type=$type --ttl=$ttl "$data"; | |
done | |
$dns transaction add -z $DNS_ZONE --name="$DNS_NAME" --ttl=60 --type "$TYPE" "$DATA" | |
$dns transaction execute -z $DNS_ZONE | |
} | |
if [ x"$DNS_ZONE" == x"" ] ; then | |
echo "Skipping dns setup: missing metadata." | |
exit 1 | |
fi | |
case $1 in | |
start) replace_dns A $PUBLIC_IP ;; | |
restart) replace_dns A $PUBLIC_IP ;; | |
stop) replace_dns CNAME ghs.googlehosted.com. ;; | |
esac | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment