Skip to content

Instantly share code, notes, and snippets.

@jcvenegas
Last active June 27, 2020 05:09
Show Gist options
  • Save jcvenegas/9d9f5631c1f3b46f9d5fefe066c67300 to your computer and use it in GitHub Desktop.
Save jcvenegas/9d9f5631c1f3b46f9d5fefe066c67300 to your computer and use it in GitHub Desktop.
azure_create.sh
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
#az login;
vm_name="${1:-}"
if [ "${vm_name}" == "" ]; then
echo "missing arg, vm-name"
exit
fi
resource_group="jcvenega-cse"
image="Canonical:UbuntuServer:18.04-LTS:latest"
user="jcvenega"
public_key="${HOME}/.ssh/id_rsa.pub"
# The UTC time of day the schedule will occur every day. Format: hhmm. Example: 1730.
# 7 pm gdl to UTC : 12:00 am = 00:00 - > 0000
shutdown_time="0000"
email_notification="[email protected]"
location="westus2"
out=$(az vm create \
--resource-group "${resource_group}" \
--name "${vm_name}" \
--image "${image}" \
--admin-username "${user}" \
--ssh-key-values "${public_key}" \
--size Standard_D4s_v3 \
--location "${location}")
ssh_script="ssh-${vm_name}.sh"
scp_script="scp-${vm_name}.sh"
start_script="start-${vm_name}.sh"
ip_file="${vm_name}_ip"
cat > "${ip_file}" << EOM
IP=$(echo "${out}" | jq -r .publicIpAddress)
EOM
cat > "${start_script}" << EOM
az vm start -g ${resource_group} --name ${vm_name}
EOM
chmod +x "${start_script}"
cat > "${ssh_script}" << EOT
#!/bin/bash
# Ask azure for vm IP, require to be logged in azure.
# Useful if stop VM but IP changes
ASK_IP=\${ASK_IP:-false}
if [ "\${ASK_IP}" == "true" ]; then
az vm list-ip-addresses -g ${resource_group} -n ${vm_name}
IP=\$(az vm list-ip-addresses -g ${resource_group} -n ${vm_name} | jq -r '.[0].virtualMachine.network.publicIpAddresses[0].ipAddress')
cat > "${ip_file}" << EOM
IP=\${IP}
EOM
else
source "${ip_file}"
fi
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "${user}@\${IP}"
EOT
chmod +x "${ssh_script}"
cat > "${scp_script}" << EOT
#!/bin/bash
path_target=\${1}
if [ "\${path_target}" == "" ]; then
echo "missing path to get"
exit 1
fi
source "${ip_file}"
scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "${user}@\${IP}:\${path_target}" .
EOT
chmod +x "${scp_script}"
az vm auto-shutdown -g "${resource_group}" -n "${vm_name}" --time "${shutdown_time}" --email "${email_notification}" -l "${location}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment