PowerShell 技能连载 - Azure多云成本优化实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function Get-AzureCostAnalysis {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,
[datetime]$StartDate = (Get-Date).AddDays(-30)
)

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ResourceAnalysis = @()
CostRecommendations = @()
}

foreach ($subId in $SubscriptionIds) {
Set-AzContext -SubscriptionId $subId | Out-Null

# 获取资源消耗数据
$resources = Get-AzResource | Where-Object {
$_.ResourceType -notin @('Microsoft.Resources/deployments','Microsoft.Resources/subscriptions')
}

$resourceGroups = $resources | Group-Object ResourceGroupName
foreach ($rg in $resourceGroups) {
$costData = Get-AzConsumptionUsageDetail -StartDate $StartDate -EndDate (Get-Date) -ResourceGroup $rg.Name

$report.ResourceAnalysis += [PSCustomObject]@{
Subscription = $subId
ResourceGroup = $rg.Name
TotalCost = ($costData | Measure-Object PretaxCost -Sum).Sum
UnderutilizedVMs = $rg.Group.Where{ $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' }.Count
}
}
}

# 生成优化建议
$report.ResourceAnalysis | ForEach-Object {
if ($_.UnderutilizedVMs -gt 5) {
$report.CostRecommendations += [PSCustomObject]@{
Recommendation = "调整资源组 $($_.ResourceGroup) 中未充分利用的VM规模"
PotentialSavings = "预计节省 $([math]::Round($_.TotalCost * 0.3)) 美元"
}
}
}

$report | Export-Excel -Path "$env:TEMP/AzureCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $report
}

核心功能

  1. 跨订阅资源消耗分析
  2. 闲置VM资源自动识别
  3. 成本节约潜力预测
  4. Excel报告自动生成

典型应用场景

  • 企业多云成本可视化管理
  • FinOps实践中的资源优化
  • 预算执行情况跟踪
  • 云服务商比价数据支持

PowerShell 技能连载 - 多云成本优化自动化系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function Get-CloudCostReport {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,

[ValidateSet('Daily','Monthly')]
[string]$Granularity = 'Monthly'
)

$costReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
TotalCost = 0
ServiceBreakdown = @{}
OptimizationSuggestions = @()
}

try {
# 获取跨云成本数据
$costData = $SubscriptionIds | ForEach-Object {
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$_/providers/Microsoft.CostManagement/query?api-version=2023-03-01" \
-Headers @{ Authorization = "Bearer $env:AZURE_TOKEN" } \
-Body (@{
type = "ActualCost"
timeframe = "MonthToDate"
dataset = @{
aggregation = @{
totalCost = @{
name = "Cost"
function = "Sum"
}
}
grouping = @(
@{
type = "Dimension"
name = "ServiceName"
}
)
}
} | ConvertTo-Json)
}

# 分析成本结构
$costReport.TotalCost = ($costData.properties.rows | Measure-Object -Property [0] -Sum).Sum
$costReport.ServiceBreakdown = $costData.properties.rows |
Group-Object { $_[1] } -AsHashTable |
ForEach-Object { @{$_.Key = [math]::Round($_.Value[0],2)} }

# 生成优化建议
$costData.properties.rows | Where-Object { $_[0] -gt 1000 } | ForEach-Object {
$costReport.OptimizationSuggestions += [PSCustomObject]@{
Service = $_[1]
Cost = $_[0]
Recommendation = "考虑预留实例或自动缩放配置"
}
}
}
catch {
Write-Error "成本数据获取失败: $_"
}

# 生成Excel格式报告
$costReport | Export-Excel -Path "$env:TEMP/CloudCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $costReport
}

核心功能

  1. 跨云成本数据聚合分析
  2. 服务维度费用结构分解
  3. 智能优化建议生成
  4. Excel格式报告输出

应用场景

  • 多云环境成本监控
  • 预算超支预警
  • 资源使用效率优化
  • 财务部门合规报告