Last active
January 11, 2022 10:25
-
-
Save rayjanoka/cf91f32b3625bd28e009bb76c7198452 to your computer and use it in GitHub Desktop.
Enable Tailscale Subnet Routes via API
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
#!/usr/bin/env sh | |
set -e | |
if [ "$TAILSCALE_APIKEY" = "" ]; then | |
echo "Missing TAILSCALE_APIKEY environment variable, exiting"; exit 21 | |
fi | |
NAME="$(hostname -f)" | |
TAILSCALE_API="https://api.tailscale.com/api/v2" | |
TAILSCALE_NET="yourDomain.com" | |
# jq can create this output for you if the cidrs are in an array | |
# echo '{"cidrs": ["10.0.0.0/24","10.0.1.0/24"]}' | jq -r '.cidrs | @csv' | |
TAILSCALE_SUBNET_ROUTES='"10.0.0.0/24","10.0.1.0/24"' | |
# Dependencies for Alpine Linux | |
if [ -f "/etc/alpine-release" ]; then | |
echo "Installing curl & jq" | |
apk add jq curl | |
fi | |
echo "Hostname: $NAME" | |
echo "Routes: $TAILSCALE_SUBNET_ROUTES" | |
echo "Searching for this machine in the list of registered machines..." | |
INDEX=0 | |
# Search for the device (machine), if it was just registered and it doesn't return at first we'll keep trying | |
while [ "$DEVICE_ID" = "" ]; do | |
DEVICE_ID=$( | |
curl -s --retry 5 -u "${TAILSCALE_APIKEY}:" "${TAILSCALE_API}/tailnet/${TAILSCALE_NET}/devices" | \ | |
jq -r --arg HOSTNAME "$NAME" '.devices[] | select(.hostname==$HOSTNAME) | .id' | |
) | |
# Timeout after ~5 minutes | |
if [ $INDEX -gt 55 ]; then | |
echo "Timeout: Unable to find $NAME in the list of registered machines" | |
exit 22 | |
fi | |
if [ "$DEVICE_ID" = "" ]; then | |
INDEX=$(( $INDEX + 1 )) | |
sleep 5 | |
fi | |
done | |
echo "Found this machine registered with ID: $DEVICE_ID" | |
echo "Enabling routes:" | |
curl -s --retry 5 -u "${TAILSCALE_APIKEY}:" "${TAILSCALE_API}/device/${DEVICE_ID}/routes" \ | |
--data-binary "{\"routes\": [${TAILSCALE_SUBNET_ROUTES}]}" | jq . |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment