PowerShell ile Azure Cost Budget ve Harcama Limitleri Yönetimi

Azure bütçeleri, harcamalarınızı belirli eşiklerde uyarı ile takip etmenizi sağlar. PowerShell ile bütçe oluşturabilir, uyarı eşikleri belirleyebilir ve aşım durumunda otomatik aksiyonlar tetikleyebilirsiniz.

Abonelik Düzeyinde Bütçe Oluşturmak

PowerShell

$subscriptionId = (Get-AzContext).Subscription.Id
$token   = (Get-AzAccessToken).Token
$token = ConvertFrom-SecureString -SecureString $Token -AsPlainText
$headers = @{ Authorization = "Bearer $token"; "Content-Type" = "application/json" }
 
$startDate = (Get-Date -Day 1).ToString("yyyy-MM-dd")
$endDate   = (Get-Date -Day 1).AddYears(1).ToString("yyyy-MM-dd")
 
$budget = @{
    properties = @{
        category     = "Cost"
        amount       = 50
        timeGrain    = "Monthly"
        timePeriod   = @{ startDate = $startDate; endDate = $endDate }
        notifications = @{
            "Alert80Pct" = @{
                enabled       = $true
                operator      = "GreaterThan"
                threshold     = 80
                contactEmails = @("finops@towershell.com","platform-team@towershell.com")
                thresholdType = "Actual"
            }
            "Alert100Pct" = @{
                enabled       = $true
                operator      = "GreaterThan"
                threshold     = 100
                contactEmails = @("cto@towershell.com","finops@towershell.com")
                thresholdType = "Actual"
            }
        }
    }
} | ConvertTo-Json -Depth 10
 
$budgetUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Consumption/budgets/MonthlyBudget?api-version=2023-05-01"
Invoke-RestMethod -Uri $budgetUrl -Method Put -Headers $headers -Body $budget
Write-Host "Butce olusturuldu: 50 USD/ay" -ForegroundColor Green
 

Resource Group Bazında Bütçeler

PowerShell

$resourceGroups =  Get-AzResourceGroup -Name aks-rg | Where { $_.Tags["Environment"] -eq "Restricted" } -ErrorAction SilentlyContinue
 
foreach ($rg in $resourceGroups) {
    $rgBudget = @{
        properties = @{
            category  = "Cost"; amount = 500; timeGrain = "Monthly"
            timePeriod = @{ startDate = $startDate; endDate = $endDate }
            filter = @{ dimensions = @{ name = "ResourceGroupName"; operator = "In"; values = @($rg.ResourceGroupName) } }
            notifications = @{
                "RGAlert90" = @{ enabled = $true; operator = "GreaterThan"; threshold = 90
                    contactEmails = @("team@towershell.com"); thresholdType = "Actual" }
            }
        }
    } | ConvertTo-Json -Depth 10
    
    $rgBudgetUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Consumption/budgets/$($rg.ResourceGroupName)-Budget?api-version=2023-05-01"
    Invoke-RestMethod -Uri $rgBudgetUrl -Method Put -Headers $headers -Body $rgBudget
    Write-Host "RG butcesi: $($rg.ResourceGroupName) - 30 USD" -ForegroundColor Cyan
}