如何通过Azure Automation Webhook或Management API向PowerShell Runbook传参
Azure Automation Runbook 传参方法(Webhook + Management API)
问题背景
我尝试通过Webhook执行Azure Automation PowerShell Runbook,但不清楚如何向PowerShell脚本传递参数。
现有调用Webhook的PowerShell代码:
$webhook = "https://ajsiyeqw12-732y-243z-9zashysdg.webhook.us.azure-automation.net/webhooks?token=asjfhhye232874829mxsdxbsahfts" Invoke-WebRequest -Method Post -Uri $webhook
底层带参数的PowerShell Runbook代码:
Param( [string]$resourceGroup, [string]$VMName, [string]$method, [string]$UAMI )
以下是两种方式的传参解决方案:
一、Webhook 传参方法
Webhook调用Runbook时,参数需放在POST请求的**请求体(Body)**中,以JSON格式传递。修改后的调用代码如下:
$webhookUri = "https://ajsiyeqw12-732y-243z-9zashysdg.webhook.us.azure-automation.net/webhooks?token=asjfhhye232874829mxsdxbsahfts" # 构造参数JSON,键名需与Runbook Param块中的参数名完全匹配 $params = @{ resourceGroup = "你的资源组名称" VMName = "你的虚拟机名称" method = "操作方法(如Start/Stop)" UAMI = "用户分配托管标识ID" } | ConvertTo-Json # 发送带参数的POST请求,必须指定JSON内容类型 Invoke-WebRequest -Method Post -Uri $webhookUri -Body $params -ContentType "application/json"
注意事项
- 必须添加
-ContentType "application/json",否则Runbook无法正确解析参数 - JSON键名与Runbook参数名严格区分大小写
- 参数值包含特殊字符时,需确保JSON转义正确
二、Management API 传参方法
使用Azure Automation管理API创建作业时,参数需放在请求体的parameters字段中。以下是PowerShell调用示例:
1. 获取Azure AD访问令牌
# 登录Azure(未登录时执行) Connect-AzAccount # 获取当前上下文并生成访问令牌 $context = Get-AzContext $token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate( $context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://management.azure.com/" ).AccessToken
2. 调用API创建带参数的Runbook作业
# 替换为实际的订阅ID、资源组、自动化账户名称 $apiUri = "https://management.azure.com/subscriptions/你的订阅ID/resourceGroups/自动化账户资源组/providers/Microsoft.Automation/automationAccounts/你的自动化账户名称/jobs?api-version=2023-11-01" # 构造请求体,指定Runbook名称和参数 $body = @{ properties = @{ runbook = @{ name = "你的Runbook名称" } parameters = @{ resourceGroup = "你的资源组名称" VMName = "你的虚拟机名称" method = "操作方法(如Start/Stop)" UAMI = "用户分配托管标识ID" } } } | ConvertTo-Json # 发送API请求 Invoke-RestMethod -Method Post -Uri $apiUri -Headers @{ "Authorization" = "Bearer $token" "Content-Type" = "application/json" } -Body $body
注意事项
- 替换URI中的占位符为实际资源信息
- 使用最新稳定版API版本(示例为2023-11-01)
- 参数名需与Runbook定义完全匹配
- 确保当前账户拥有
Microsoft.Automation/automationAccounts/jobs/write权限
内容的提问来源于stack exchange,提问作者pbj
相关产品推荐
相关产品推荐

