This script is used to automate the shutdown and startup of virtual machines in Azure based on their tags.
The script starts by connecting to Azure using the Connect-AzAccount
cmdlet and managed identity, which provides the necessary authentication and authorization to access the Azure resources.
Next, it gets all virtual machines that have a ShutdownTime
tag and StartTime
tag using the Get-AzVM
cmdlet and Where-Object
cmdlet.
For each virtual machine, the script checks the value of the ShutdownTime
tag and compares it with the current time. If the difference is less than or equal to 80 minutes and greater than or equal to zero, the script shuts down the virtual machine using the Stop-AzVM
cmdlet.
Similarly, for each virtual machine, the script checks the value of the StartTime
tag and compares it with the current time. If the difference is less than or equal to 60 minutes and greater than or equal to zero, the script starts up the virtual machine using the Start-AzVM
cmdlet.
Finally, the script outputs a message to indicate the action taken on each virtual machine.
To run this script in an Azure Automation account using a managed identity, you need to follow these steps:
-
Create an Azure Automation account in your subscription.
-
Enable the managed identity for the Azure Automation account.
-
Assign a role to the managed identity to access the virtual machines.
-
Create a runbook in the Azure Automation account and copy the script.
-
Schedule the runbook to run on whatever schedule you need.
-
Save and publish the runbook.
-
Set the ShutdownTime and StartTime tag on Azure VMs that you want to shutdown and startup with a value of HH:mm i.e 18:30
or refer to [https://learn.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation]