Skip to content

Instantly share code, notes, and snippets.

@ansgarkroger
Forked from akisys/azure-bastion-connect.sh
Created November 22, 2024 16:26
Show Gist options
  • Save ansgarkroger/e54bda5b7cb1d18246c77440a7af848a to your computer and use it in GitHub Desktop.
Save ansgarkroger/e54bda5b7cb1d18246c77440a7af848a to your computer and use it in GitHub Desktop.
Use Azure Bastion with ssh-user-config blocks
#!/usr/bin/env bash
set -fu
destination="${1:-""}"
port="${2:-"8122"}"
timeout="${3:-""}" # this will auto-terminate the azure bastion tunnel after this many seconds
azure_bastion_opts=""
if [ -n "${timeout}" ];
then
azure_bastion_opts="${azure_bastion_opts} --timeout ${timeout}"
fi
case "${destination}" in
static-vm-connection-example)
_bastion_host="AzureBastionResourceName"
_rg_name="AZBastionResourceGroupName"
_subscription="AZBastionSubscriptionID"
_target_port="22"
_map_port="${port}"
_target_id="VMResourceID"
azure_bastion_opts="$(/usr/bin/printf \
" -n %s -g %s --subscription %s --target-resource-id %s --resource-port %d --port %d %s" \
"${_bastion_host}" \
"${_rg_name}" \
"${_subscription}" \
"${_target_id}" \
"${_target_port}" \
"${_map_port}" \
"${azure_bastion_opts}"
)"
proc_check=" \-\-target-resource-id ${_target_id}"
;;
dynamic-vmscaleset-connection-example)
_bastion_host="AzureBastionResourceName"
_rg_name="AZBastionResourceGroupName"
_subscription="AZBastionSubscriptionID"
_target_port="22"
_map_port="${port}"
_target_id="$(az vmss list-instances --subscription VMSSSubscription -g VMSSResourceGroupName -n VMSSName --query '[].id' -o tsv)"
azure_bastion_opts="$(/usr/bin/printf \
" -n %s -g %s --subscription %s --target-resource-id %s --resource-port %d --port %d %s" \
"${_bastion_host}" \
"${_rg_name}" \
"${_subscription}" \
"${_target_id}" \
"${_target_port}" \
"${_map_port}" \
"${azure_bastion_opts}"
)"
proc_check=" \-\-target-resource-id ${_target_id}"
;;
*)
exit 1
;;
esac
function fn_cleanup() {
if ! pgrep "nc localhost ${port}"; then
pkill -f "${proc_check}"
fi
}
if [ -n "${azure_bastion_opts}" ];
then
trap fn_cleanup SIGTERM SIGINT SIGHUP SIGABRT
AZTUNNEL_PID=$(pgrep -f "${proc_check}")
if [ -z "${AZTUNNEL_PID}" ];
then
az network bastion tunnel $azure_bastion_opts &
sleep 2
fi
## need to provide an open session :P
nc localhost ${port}
fi
Host static-vm-connection-example
Port 52121
ProxyCommand bash -c "~/.ssh/azure-bastion-connect.sh %h %p"
Host dynamic-vmscaleset-connection-example
Port 52122
ProxyCommand bash -c "~/.ssh/azure-bastion-connect.sh %h %p"
## this might be required if the VMSS instances change
StrictHostKeyChecking no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment