How to Automate Tailscale Exit Node




When I am away from home I want to use my Tailscale exit node. When I am at home I don’t need the exit node. Remembering to enable it or disable it doesn’t always happen. So, I automated it.

My setup is on a MacBook Air, and I have an eero router at home. The values and commands I used are for that environment.

Step 1 - The script

The script compares the router IP address and netmask to my home values. If they match, I’m at home and the exit node can be turned off. If they don’t match, I’m away and the exit node should be enabled. Save the script as ~/.local/bin/ts-exit-auto and make sure it is executable ( chmod +x ).

#!/bin/bash
# vim: set filetype=bash :
TS="/Applications/Tailscale.app/Contents/MacOS/Tailscale"
EXIT_NODE="gluon"
HOME_GW="192.168.4.1"
HOME_MASK="255.255.252.0"
LOG="$HOME/Library/Logs/ts-exit-auto.log"

sleep 5

at_home=false
for ifc in $(ifconfig -l); do
  gw=$(ipconfig getoption "$ifc" router 2>/dev/null) || continue
  mask=$(ipconfig getoption "$ifc" subnet_mask 2>/dev/null)
  [[ "$gw" == "$HOME_GW" && "$mask" == "$HOME_MASK" ]] && at_home=true && break
done

if "$at_home"; then
  "$TS" set --exit-node= && echo "$(date): home, exit node off" >> "$LOG"
else
  "$TS" set --exit-node="$EXIT_NODE" --exit-node-allow-lan-access && echo "$(date): away, exit node $EXIT_NODE" >> "$LOG"
fi

Test the script prior to setting up the LaunchAgent. If it doesn’t appear to be working, try running it with tracing ( -x ) turned on.

bash -x ~/.local/bin/ts-exit-auto 2>&1 | grep -E 'gw=|mask=|\[\['

Step 2 - The Launch Agent

You will need to change /Users/mark to your actual home. launchd won’t expand ~, and my $HOME probably won’t work for you. Save the plist as ~/Library/LaunchAgents/com.mark.ts-exit-auto.plist. Substitute your user name for mark.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>com.mark.ts-exit-auto</string>
  <key>ProgramArguments</key>
  <array><string>/Users/mark/.local/bin/ts-exit-auto</string></array>
  <key>WatchPaths</key>
  <array><string>/Library/Preferences/SystemConfiguration</string></array>
  <key>RunAtLoad</key><true/>
</dict>
</plist>

Step 3 - Load it

Load the Launch Agent:

launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.mark.ts-exit-auto.plist

Notes