通过Webhook的Azure启动/停止VM

时间:2019-04-23 14:01:03

标签: azure azure-powershell

我们在azure环境中有多个具有多个资源组的VM。一些资源组具有多个VM。我们现在正在使用将启动或停止VM的URL触发器webhook。这是可行的,但是当一个资源组包含多个VM时,所有VM将启动,或者所有VM将停止而不是您要启动/停止的VM。

尝试了多个脚本,但无法正常工作或给我错误。

    param(
  [Parameter(Mandatory=$false)]
  [object] 
  $WebHookData
 )  

write output "Data WebHook $WebHookData"

#retrieve ResourceGroup
$ResourceGroupName = $WebHookData.RequestBody
write output "Data ResourceGroup $ResourceGroupName"

$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint

$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName

    if(!$VMs) 
    {
        Write-Output -InputObject 'No VMs were found in the specified Resource Group.'
    }
    else 
    {
        ForEach ($VM in $VMs) 
        {
            $StartVM = Stop-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VM.Name -Force #-ErrorAction SilentlyContinue


        } 
    } 

$message = ConvertTo-Json -Compress -InputObject ([ordered]@{
       headers = @{'content-type' = 'text/plain'}
          body = ''
    statusCode = 200
})

1 个答案:

答案 0 :(得分:0)

您可以在 启动/停止 虚拟机中尝试以下脚本。

启动虚拟机

$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$null = Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$VMs = Get-AzureRmResource|Where-Object {$_.Tags.Keys -eq "owner" -and $_.Tags.Values -eq "daneum"}
foreach ($VM in $VMs) {
    if ($VM.ResourceType -eq "Microsoft.Compute/virtualMachines") {
        Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose
    }
}

停止VM

$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$null = Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
$VMs = Get-AzureRmResource|Where-Object {$_.Tags.Keys -eq "owner" -and $_.Tags.Values -eq "daneum"}
foreach ($VM in $VMs) {
    if ($VM.ResourceType -eq "Microsoft.Compute/virtualMachines") {
        Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Verbose
    }
}

对于Webhook集成过程,您可以查看here