Skip to content

Instantly share code, notes, and snippets.

@sinmetal
Created April 18, 2017 10:04
Show Gist options
  • Save sinmetal/9368fe256d375f4d6ed89c96e6bab235 to your computer and use it in GitHub Desktop.
Save sinmetal/9368fe256d375f4d6ed89c96e6bab235 to your computer and use it in GitHub Desktop.
Cloud DNSのRecordを、動作しているCompute EngineのGlobal IP Addrに変更する。元ネタは http://stackoverflow.com/questions/34726498/how-to-update-google-cloud-dns-with-ephemeral-ip-for-an-instance
#!/bin/bash
ttlify() {
local i
for i in "$@"; do
[[ "${i}" =~ ^([0-9]+)([a-z]*)$ ]] || continue
local num="${BASH_REMATCH[1]}"
local unit="${BASH_REMATCH[2]}"
case "${unit}" in
weeks|week|wee|we|w) unit=''; num=$[num*60*60*24*7];;
days|day|da|d) unit=''; num=$[num*60*60*24];;
hours|hour|hou|ho|h) unit=''; num=$[num*60*60];;
minutes|minute|minut|minu|min|mi|m) unit=''; num=$[num*60];;
seconds|second|secon|seco|sec|se|s) unit=''; num=$[num];;
esac
echo "${num}${unit}"
done
}
dns_start() {
gcloud dns record-sets transaction start -z "${ZONENAME}"
}
dns_info() {
gcloud dns record-sets transaction describe -z "${ZONENAME}"
}
dns_abort() {
gcloud dns record-sets transaction abort -z "${ZONENAME}"
}
dns_commit() {
gcloud dns record-sets transaction execute -z "${ZONENAME}"
}
dns_add() {
if [[ -n "$1" && "$1" != '@' ]]; then
local -r name="$1.${ZONE}."
else
local -r name="${ZONE}."
fi
local -r ttl="$(ttlify "$2")"
local -r type="$3"
shift 3
gcloud dns record-sets transaction add -z "${ZONENAME}" --name "${name}" --ttl "${ttl}" --type "${type}" "$@"
}
dns_del() {
if [[ -n "$1" && "$1" != '@' ]]; then
local -r name="$1.${ZONE}."
else
local -r name="${ZONE}."
fi
local -r ttl="$(ttlify "$2")"
local -r type="$3"
shift 3
gcloud dns record-sets transaction remove -z "${ZONENAME}" --name "${name}" --ttl "${ttl}" --type "${type}" "$@"
}
lookup_dns_ip() {
host "$1" | sed -rn 's@^.* has address @@p'
}
my_ip() {
curl "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip" -H "Metadata-Flavor: Google"
}
doit() {
ZONE=sinmetal.org
ZONENAME=sinmetal-org
dns_start
dns_del $HOSTNAME 5min A `lookup_dns_ip "$HOSTNAME.${ZONE}."`
dns_add $HOSTNAME 5min A `my_ip`
dns_commit
}
doit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment