使用ARM模板创建Availability Test时遇到请求内容无效错误
Azure Availability Test创建失败问题解决
问题背景
已通过Python SDK完成资源组、AKS集群、Log Analytics工作区及Application Insights的创建,但通过ARM模板调用Azure REST API创建Availability Test时持续返回400错误。
原代码
availability_test = { "$schema": "ttps://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "apiVersion": "2019-04-01", "name": app_insights_name, "type": "microsoft.insights/webtests", "location": "eastus2", "properties": { "SyntheticMonitorId": None, "Enabled": True, "Locations": [ { "Id": "us-ca-sjc-azr" } ], "Configuration": { "WebTest": { "Timeout": "60", "ParseDependentRequests": False, "FollowRedirects": True } } } } ] } deployment_url = f"https://management.azure.com/subscriptions/{subscription_id}/resourcegroups/{resource_group_name}/providers/microsoft.resources/deployments/{app_insights_name}?api-version=2023-07-01" headers = { "Authorization": f"Bearer {credentials.get_token('https://management.azure.com/.default').token}", "Content-Type": "application/json" } response = requests.put(deployment_url, data=json.dumps(availability_test), headers=headers) if response.status_code == 201: print("Availability test deployed successfully!") else: print(f"Failed to deploy availability test. Status code: {response.status_code}") print(response.text)
报错信息
Failed to deploy availability test. Status code: 400 {"error":{"code":"InvalidRequestContent","message":"The request content was invalid and could not be deserialized: 'Could not find member '$schema' on object of type 'DeploymentContent'. Path '$schema', line 1, position 11.'."}}
错误原因
Azure资源部署API(microsoft.resources/deployments)接收的请求体是DeploymentContent格式,而非直接的ARM模板内容。原代码将包含$schema的ARM模板根对象直接作为请求体,不符合API要求,导致序列化失败。
同时原代码还存在其他问题:
$schemaURL缺失h,应为https://...SyntheticMonitorId不能设为None,必须与WebTest的名称一致- WebTest配置缺少核心的
Request字段(如目标URL),无法创建有效测试
修复后的REST API调用代码
将ARM模板包裹在properties.template字段中,并补充部署模式(mode),同时修正其他问题:
# 修正后的ARM模板内容 availability_test_template = { "$schema": "https://management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "apiVersion": "2020-02-02-preview", # 使用较新的API版本 "name": app_insights_name, "type": "microsoft.insights/webtests", "location": "eastus2", "properties": { "SyntheticMonitorId": app_insights_name, # 与name保持一致 "Enabled": True, "Locations": [ { "Id": "us-ca-sjc-azr" } ], "Configuration": { "WebTest": """<WebTest Name="SampleTest" Id="YOUR_TEST_ID" Enabled="True" CssProjectStructure="" CssIteration="" Timeout="60" WorkItemIds="" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" Description="" CredentialUserName="" CredentialPassword="" PreAuthenticate="True" Proxy="default" StopOnError="False" RecordedResultFile="" ResultsLocale=""> <Items> <Request Method="GET" Guid="YOUR_REQUEST_GUID" Version="1.1" Url="https://your-target-url.com" ThinkTime="0" Timeout="60" ParseDependentRequests="False" FollowRedirects="True" RecordResult="True" Cache="False" ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="200" ExpectedResponseUrl="" ReportingName="" IgnoreHttpStatusCode="False" /> </Items> </WebTest>""" }, "Kind": "ping" # 指定测试类型,ping为简单可用性测试 } } ] } # 构造符合DeploymentContent格式的请求体 deployment_content = { "properties": { "mode": "Incremental", # 增量部署模式 "template": availability_test_template } } deployment_url = f"https://management.azure.com/subscriptions/{subscription_id}/resourcegroups/{resource_group_name}/providers/microsoft.resources/deployments/{app_insights_name}_deployment?api-version=2023-07-01" headers = { "Authorization": f"Bearer {credentials.get_token('https://management.azure.com/.default').token}", "Content-Type": "application/json" } response = requests.put(deployment_url, data=json.dumps(deployment_content), headers=headers) if response.status_code in [200, 201]: print("Availability test deployed successfully!") else: print(f"Failed to deploy availability test. Status code: {response.status_code}") print(response.text)
更简便的替代方法:使用Azure Python SDK直接创建
既然已经在使用Python SDK,推荐直接用azure-mgmt-appinsights库创建WebTest(即Availability Test),无需手动构建ARM模板和REST请求:
- 先安装依赖:
pip install azure-mgmt-appinsights azure-identity
- 创建测试的代码示例:
from azure.identity import DefaultAzureCredential from azure.mgmt.applicationinsights import ApplicationInsightsManagementClient from azure.mgmt.applicationinsights.models import WebTest, WebTestProperties, WebTestGeolocation # 初始化客户端 credential = DefaultAzureCredential() subscription_id = "YOUR_SUBSCRIPTION_ID" resource_group_name = "YOUR_RESOURCE_GROUP" app_insights_name = "YOUR_APP_INSIGHTS_NAME" webtest_name = "YOUR_AVAILABILITY_TEST_NAME" client = ApplicationInsightsManagementClient(credential, subscription_id) # 定义测试属性 webtest_properties = WebTestProperties( synthetic_monitor_id=webtest_name, enabled=True, locations=[WebTestGeolocation(id="us-ca-sjc-azr")], configuration="""<WebTest Name="SampleTest" Id="YOUR_TEST_ID" Enabled="True" Timeout="60" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> <Items> <Request Method="GET" Url="https://your-target-url.com" Timeout="60" ParseDependentRequests="False" FollowRedirects="True" ExpectedHttpStatusCode="200" /> </Items> </WebTest>""", kind="ping" ) # 创建测试 webtest = client.web_tests.create_or_update( resource_group_name=resource_group_name, web_test_name=webtest_name, web_test=WebTest( location="eastus2", properties=webtest_properties ) ) print(f"Availability test created successfully: {webtest.id}")
内容的提问来源于stack exchange,提问作者maj1n
相关产品推荐
相关产品推荐

