PowerShell ile Azure Automation Runbook Oluşturmak ve Yayınlamak

Azure Automation Runbook’ları, tekrarlayan yönetim görevlerini bulutta çalıştırmanıza olanak tanır. PowerShell ile runbook oluşturabilir, yayınlayabilir ve zamanlanmış görevler kurabilirsiniz. ManagedID ve hedef kaynaktaki yetki durumuna dikkat!

Automation Account Oluşturmak

PowerShell
$resourceGroup    = "vpntest "
$automationAccount = " automationacc00009"
$location          = "uksouth"
 
New-AzAutomationAccount `
    -ResourceGroupName $resourceGroup `
    -Name $automationAccount `
    -Location $location `
    -Plan "Basic"
Write-Host "Automation Account olusturuldu." -ForegroundColor Green
 

Runbook Script Dosyası Oluşturmak

PowerShell
$scriptContent = @'
param([string]$ResourceGroup = "vpntest")
Connect-AzAccount -Identity
$vms = Get-AzVM -ResourceGroupName $ResourceGroup
foreach ($vm in $vms) {
    $status = (Get-AzVM -Name $vm.Name -Status).Statuses | Where-Object { $_.Code -like "PowerState*" }
    if ($status.DisplayStatus -eq "VM running") {
        Stop-AzVM -Name $vm.Name -ResourceGroupName $ResourceGroup -Force | Out-Null
        Write-Output "Durduruldu: $($vm.Name)"
    }
}
'@
$scriptPath = "Stop-UnusedVMs.ps1"
$scriptContent | Out-File $scriptPath -Encoding UTF8
 

Runbook’u İçe Aktarmak ve Yayınlamak

PowerShell
Import-AzAutomationRunbook `
    -ResourceGroupName vpntest `
    -AutomationAccountName "automationacc00009"`
    -Name "Stop-UnusedVMs" `
    -Type PowerShell `
    -Path "Stop-UnusedVMs.ps1" | out-null
 
Publish-AzAutomationRunbook `
    -ResourceGroupName vpntest `
    -AutomationAccountName "automationacc00009"` `
    -Name "Stop-UnusedVMs" | out-null
Write-Host "Runbook yayınlandı." -ForegroundColor Green