Azure DevOps REST API创建ARM服务连接验证报错:重复键已添加
Azure ARM服务连接创建验证失败问题解决
问题描述
通过REST API创建Azure ARM手动服务连接时,无法完成验证,报错:An item with the same key has already been added。
通过Azure DevOps GUI将服务主体密码修改为其他值会触发密码错误,但改回REST API使用的原密码后,连接即可验证通过,推测REST API创建流程存在异常。
问题分析
该报错核心原因是请求体存在重复键值对,或API版本/结构不符合Azure DevOps要求,结合提供的代码,可能的诱因包括:
- 请求体
data或authorization.parameters中存在冗余字段,导致API解析时出现键重复 - 使用的预览版API(5.1-preview.2)存在字段处理bug
- 手动设置
isReady为$True,干扰了服务连接的初始化验证逻辑
解决方案
1. 精简请求体,移除冗余字段
删除data中的CreationMode、scopeLevel字段,同时去掉手动设置的isReady字段,让API自动处理初始化状态:
$Body = [pscustomobject]@{ data = [pscustomobject]@{ subscriptionId = "$SubscriptionId" subscriptionName = "$subscriptionName" } authorization = [pscustomobject]@{ scheme = 'ServicePrincipal' parameters = [pscustomobject]@{ tenantid = "$TenantID" serviceprincipalid = "$AADApplicationID" authenticationType = "spnKey" serviceprincipalkey = "$SPKey" } } isShared = $true serviceEndpointProjectReferences = @( @{ projectReference = @{ id = "9a4bfcab-c7b2-48fb-90c8-efb7461a962f" name = "CescomIaC" } name = "$SubscriptionId" } ) name = "$SubscriptionId" type = 'azurerm' url = 'https://management.azure.com/' } | ConvertTo-Json -Depth 10
2. 升级API版本至稳定预览版
将创建服务连接的API版本从5.1-preview.2升级到7.1-preview.4,新版本修复了旧版本的字段重复解析问题:
$Uri = "https://dev.azure.com/ORG/PROJECT/_apis/serviceendpoint/endpoints?api-version=7.1-preview.4"
3. 创建后手动触发验证
若前两种方案无效,可在创建服务连接后调用验证API,替代GUI修改密码的操作:
# 创建服务连接后添加以下代码 $serviceendpointAzure = Invoke-RestMethod -Uri $Uri -Method Post -Body $Body -Headers $Headers -ContentType 'application/json' $serviceendpointAzureid = $serviceendpointAzure.id # 触发验证 $validateUri = "https://dev.azure.com/ORG/PROJECT/_apis/serviceendpoint/endpoints/$serviceendpointAzureid/validate?api-version=7.1-preview.1" Invoke-RestMethod -Uri $validateUri -Method Post -Headers $Headers -ContentType 'application/json'
验证流程
- 应用修改后重新执行脚本
- 直接在Azure DevOps中验证服务连接,确认报错是否消失
- 若问题仍存在,检查服务主体是否拥有订阅的足够权限
内容的提问来源于stack exchange,提问作者Christoffer Klarskov Jakobsen
相关产品推荐
相关产品推荐

