Skip to content

Instantly share code, notes, and snippets.

@dollarpo7
Created June 24, 2020 10:53
Show Gist options
  • Select an option

  • Save dollarpo7/f9d6130e05d03f0e99d9d1fe4c9721e1 to your computer and use it in GitHub Desktop.

Select an option

Save dollarpo7/f9d6130e05d03f0e99d9d1fe4c9721e1 to your computer and use it in GitHub Desktop.
Stop a VM using a Webhook
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
}
@dollarpo7
Copy link
Author

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`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment