This repository has been archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dealocate_vms.sh
59 lines (51 loc) · 1.96 KB
/
dealocate_vms.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#! /usr/bin/env bash
########################################################################################################
# Title: Deallocate all VMs in subscription except a specific one #
# Author: Marin Nedea #
# Created: March 19th, 2018 #
# Usage: Change the variables to your own. #
# Make sure the script has executable permissions: #
# chmod +x deallocate_vms.sh and execute the script by typing: ./deallocate_vms.sh #
# Requires: AzCli 2.0 installed on the machine you're running this script on #
# https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest #
# If enabled, you can run it through the bash Cloud Shell in your Azure Portal page. #
########################################################################################################
# Exclude VM
vmexcept=<vm name to exclude from script>
sID="<your subscription id here>"
# Set subscriptionID:
az account set --subscription $sID
# List all resource groups
declare -a rgarray="$(az group list --query '[].name' -o tsv)"
#check if array is empty
if [ -z "$rgarray" ]; then
echo "No resource group in this subscription: $sID"
exit
else
for i in ${rgarray[@]}; do
rgName=$i;
# List all VMs for each resource group rgName
declare -a vmarray="$(az vm list -g $rgName --query '[].name' -o tsv)"
#check if array is empty
if [ -z "$vmarray" ]; then
echo "No VM in "$rgName
else
for j in ${vmarray[@]}; do
vmName=$j;
#Check if VM is excluded
if [[ "$vmName" == "$vmexcept" ]]; then
echo "VM $vmName is excepted and will not be deallocated"
else
# Check if Vm is not already stopped/deallocated
vm_state="$(az vm show -g $rgName -n $vmName -d --query powerState -o tsv)"
if [[ "$vm_state" != "VM deallocated" ]] ; then
echo "Stopping/deallocating VM: $vmName "
az vm deallocate -g $rgName -n $vmName
else
echo "VM $vmName is already in deallocated state."
fi
fi
done;
fi
done;
fi