Skip to content

Instantly share code, notes, and snippets.

@domse
Created January 23, 2022 16:44
Show Gist options
  • Save domse/7fb0c657a0ed92fbbed9e2ac23f57341 to your computer and use it in GitHub Desktop.
Save domse/7fb0c657a0ed92fbbed9e2ac23f57341 to your computer and use it in GitHub Desktop.
Script for CLI booting, deallocating and status of Azure VM
import requests
import sys
AZURE_TENANT_ID="YourTenantID"
AZURE_CLIENT_ID="YourClientID"
AZURE_CLIENT_SECRET="YourClientSecret"
SUBSCRIPTON_ID="YourSubscriptionID"
RESSOURCE_GROUP_NAME="YourRessourceGroup"
VM_NAME="YourVMName"
url_gettoken = "https://login.microsoftonline.com/" + AZURE_TENANT_ID + "/oauth2/token"
url_on = "https://management.azure.com/subscriptions/" + SUBSCRIPTON_ID + "/resourceGroups/" + RESSOURCE_GROUP_NAME + "/providers/Microsoft.Compute/virtualMachines/" + VM_NAME + "/start?api-version=2021-07-01"
url_off ="https://management.azure.com/subscriptions/" + SUBSCRIPTON_ID + "/resourceGroups/" + RESSOURCE_GROUP_NAME + "/providers/Microsoft.Compute/virtualMachines/" + VM_NAME + "/deallocate?api-version=2021-07-01"
url_status = "https://management.azure.com/subscriptions/" + SUBSCRIPTON_ID + "/resourceGroups/" + RESSOURCE_GROUP_NAME + "/providers/Microsoft.Compute/virtualMachines/" + VM_NAME + "/instanceView?api-version=2021-07-01"
def gettoken():
import requests
url = url_gettoken
payload='grant_type=client_credentials&client_id=' + AZURE_CLIENT_ID + '&redirect_uri=&resource=https%3A%2F%2Fmanagement.azure.com&client_secret=' + AZURE_CLIENT_SECRET
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
return response.json()["access_token"]
if(sys.argv[1] == "start"):
token = gettoken()
api_url = url_on
headers = {
'Authorization': 'Bearer ' + token
}
response = requests.post(api_url, headers=headers)
elif (sys.argv[1] == "stop"):
token = gettoken()
api_url = url_off
headers = {
'Authorization': 'Bearer ' + token
}
response = requests.post(api_url, headers=headers)
elif (sys.argv[1] == "status"):
token = gettoken()
api_url = url_status
headers = {
'Authorization': 'Bearer ' + token
}
response = requests.get(api_url, headers=headers)
# print(response.text)
if "deallocating" in response.text:
print(True)
elif "running" in response.text:
print(True)
elif "starting" in response.text:
print(True)
elif "deallocated" in response.text:
print(False)
elif (sys.argv[1] == "token"):
gettoken()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment