Created
December 26, 2021 19:48
-
-
Save zypA13510/df2cbb59e100f5a50cfb2e1bfc398d34 to your computer and use it in GitHub Desktop.
Utility script to help GCP Compute Engine VMs to set their ephemeral IP address to Cloud DNS zone on boot.
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
[Unit] | |
Description=Update current instance IP to Cloud DNS. | |
After=network-online.target auditd.service | |
[Service] | |
#ExecStart=/opt/compute-engine-ddns.sh <zone-name> <domain> | |
Type=oneshot | |
[Install] | |
WantedBy=multi-user.target |
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 | |
# Usage: | |
# compute-engine-ddns.sh <zone-name> <domain> | |
# | |
# Example: | |
# compute-engine-ddns.sh zone-1 instance-1.example.com | |
DNS_ZONE=$1 | |
DOMAIN=$2 | |
INSTANCE_NAME=$(curl -sS http://metadata.google.internal/computeMetadata/v1/instance/name -H Metadata-Flavor:Google) | |
INSTANCE_ZONE=$(curl -sS http://metadata.google.internal/computeMetadata/v1/instance/zone -H Metadata-Flavor:Google) | |
EXISTING=$(gcloud dns record-sets list --zone="$DNS_ZONE" --name="$DOMAIN." --format="value(rrdatas)") | |
NEW_IP=$(gcloud compute instances describe "$INSTANCE_NAME" --zone="$INSTANCE_ZONE" --format="value(networkInterfaces[0].accessConfigs.natIP)") | |
if [ -n "$EXISTING" ]; then | |
gcloud dns record-sets update "$DOMAIN." --rrdatas="$NEW_IP" --type=A --zone="$DNS_ZONE" | |
else | |
gcloud dns record-sets create "$DOMAIN." --rrdatas="$NEW_IP" --type=A --zone="$DNS_ZONE" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment