Automate connecting to temporary and rotating development servers

in Mac OS


I rotate a lot of short-lived VPS instances for testing and development. A lot of them are hosted with Oracle Cloud free tier, and so rotating them is effortless: they are all created using the same instance configuration, recognize the same SSH keys etc.

On my Mac OS, however, it took me a while to finally come up with a script that makes reconnecting to each new instance as effortless. I made each instance have a one-character subdomain, and the script just prompts me for that character.

  • f.example.com is the FreeBSD instance, and I type f
  • d.example.com is the Debian instance, and I type d

And here's my oci-ssh.command script:

read -p "Instance: " os

host="${os}.example.com"
port='22'
# Default user on Debian and FreeBSD cloud images is the os name in lowercase
user=$([ "$os" = "f" ] && echo 'freebsd' || echo 'debian')

# Clean up ~/.ssh/known_hosts if this host is already there
ssh-keygen -R $host >/dev/null 2>&1
ssh-keygen -R [$host]:$port >/dev/null 2>&1

# SSH-connect, making sure we trust by default and do not clutter known hosts
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
    -i ~/.ssh/custom_key_if_needed \
    -p $port $user@$host

If a part of the testing is configuring the servers to run SSH on a custom port (e.g. 22345) and introducing another SSH user (e.g. new_ssh_user), you can have the script check that too. Replace the part where you define port and user variables with:

# Test whether port 22345 is connectable
if nc -z "$host" '22345'; then
    port='22345'
    user='new_ssh_user'
else
    # Must be not-yet-configured instance running default cloud OS image
    port='22'
    user=$([ "$os" = "f" ] && echo 'freebsd' || echo 'debian')
fi
#macos #oracle-cloud-infrastructure #ssh