Last active
June 7, 2017 16:25
-
-
Save ronoaldo/6d6f97bc20a5a40c4aac5e4fa6c09dd5 to your computer and use it in GitHub Desktop.
Cloud DNS record set configuration during instance startup.
This file contains 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 | |
# | |
# Helper script to auto-configure a Cloud DNS record during | |
# compute engine instance startup. | |
# | |
# Setup: | |
# 1. Download and install the script in the instance: | |
# curl -L https://gist.github.com/ronoaldo/6d6f97bc20a5a40c4aac5e4fa6c09dd5/raw/ > /etc/init.d/clouddns-update | |
# 2. Give this script permissions and setup as startup daemon | |
# chmod +x /etc/init.d/clouddns-update | |
# update-rc.d -f clouddns-update defaults | |
# 3. Add instance metadata: | |
# clouddns-zone: the hosted zone name (e.g. my-hosted-zone) | |
# clouddns-name: the record name (e.g. sub.domain.com) | |
# clouddns-project: (optional) if the VM project does not contains the hosted zone | |
# 4. Profit! | |
# | |
### 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/$1" | |
} | |
# Use Cloud DNS to update hostname | |
export DNS_ZONE="$(metadata 'instance/attributes/clouddns-zone')" | |
export DNS_NAME="$(metadata 'instance/attributes/clouddns-name')" | |
export DNS_PROJECT="$(metadata 'instance/attributes/clouddns-project')" | |
export PUBLIC_IP=$(metadata 'instance/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 | |
if [ x"$DNS_PROJECT" == x"" ] ; then | |
export DNS_PROJECT="$(metadata 'project/project-id')" | |
fi | |
echo "Using project id: $DNS_PROJECT" | |
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