Created
June 24, 2020 10:53
-
-
Save dollarpo7/f9d6130e05d03f0e99d9d1fe4c9721e1 to your computer and use it in GitHub Desktop.
Stop a VM using a Webhook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| param | |
| ( | |
| [Parameter (Mandatory = $false)] | |
| [object] $WebhookData | |
| ) | |
| #Get service principal details from shared resources | |
| $cred = Get-AutomationPSCredential -Name 'SPCreds' | |
| $tenantId = Get-AutomationVariable -Name 'TenantId' | |
| #Auth with service principal | |
| Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tenantId | |
| #Convert request body to PS object | |
| $vms = (ConvertFrom-Json -InputObject $WebhookData.RequestBody) | |
| Import-Module Az.Compute | |
| #Loop over each item and stop the VM | |
| foreach($vm in $vms) { | |
| Stop-AzVM -Name $vm.Name -ResourceGroup $vm.ResourceGroup -Force | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After you create a webhook for the StopVM Runbook you can use the following PowerShell snippet to invoke your Runbook via the webhook.
This example would shutdown two VMs named web1 and web2 in the "webservers" resource group:
`$uri = "https://s4events.azure-automation.net/webhooks?token="
$vms = @(
@{ Name="web1";ResourceGroup="webservers"},
@{ Name="web2";ResourceGroup="webservers"}
)
$body = ConvertTo-Json -InputObject $vms
$header = @{ message="Started by CloudSkills.io"}
Invoke-WebRequest -Method Post -Uri $uri -Body $body -Headers $header`