Skip to content

Instantly share code, notes, and snippets.

@azrsh
Last active September 6, 2023 11:24
Show Gist options
  • Save azrsh/377ca86cdaf119bb61cca8e0a2880217 to your computer and use it in GitHub Desktop.
Save azrsh/377ca86cdaf119bb61cca8e0a2880217 to your computer and use it in GitHub Desktop.
SSH to Azure Virtual Machine with Azure CLI
#!/bin/bash -e
while [[ $# -gt 0 ]]; do
case $1 in
-g|--resource-group)
group="$2"
shift
shift
;;
-n|--name)
name="$2"
shift
shift
;;
--start)
start=YES
shift
;;
*)
echo "Unknown option $1"
exit 1
;;
esac
done
if [ -z "${group}" ]; then
group="$(az group list | jq -r '.[].name' | peco --on-cancel error)"
fi
if [ -z "${name}" ]; then
name="$(az vm list -g "${group}" | jq -r '.[].name' | peco --on-cancel error)"
fi
if [ -n "${start}" ]; then
power="$(az vm get-instance-view -g "${group}" -n "${name}" --query 'instanceView.statuses[1].code' -o tsv)"
if [ "${power}" != "PowerState/running" ]; then
az vm start -g "${group}" -n "${name}"
fi
fi
az ssh vm -g "${group}" -n "${name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment