如何在Bicep中为其他资源组的Key Vault添加访问策略?
问题背景
尝试为另一个资源组中的Azure Key Vault添加访问策略,使用以下Bicep代码后执行失败:
resource Keyvault 'Microsoft.KeyVault/vaults@2021-04-01-preview' existing = { name: KeyvaultName scope: resourceGroup(ResourceGroup) } resource accessPolicy 'Microsoft.KeyVault/vaults/accessPolicies@2021-04-01-preview' = { name: '${Keyvault.id}/add' properties: { accessPolicies: [ { tenantId: subscription().tenantId objectId: UamiObjectId permissions: { keys: [] secrets: ['get'] certificates: [] } } ] } }
遇到的错误
错误1:资源ID格式不合法
Error: Code=InvalidTemplate; Message=Deployment template validation failed: 'The template resource '/subscriptions/subId/resourceGroups/rgName/providers/Microsoft.KeyVault/vaults/KeyVaultName/add' for type 'Microsoft.KeyVault/vaults/accessPolicies' has incorrect segment lengths. A nested resource type must have identical number of segments as its resource name. A root resource type must have segment length one greater than its resource name.
错误2:Scope属性使用错误
尝试给accessPolicies资源添加订阅ID作为scope时,触发:
Error BCP037: The property "scope" is not allowed on objects of type "Microsoft.KeyVault/vaults/accessPolicies". Permissible properties include "asserts", "dependsOn".
可行解决方案
该操作完全可行,问题出在Bicep嵌套资源的声明逻辑错误,正确写法如下:
正确的Bicep代码
// 引用目标资源组中的Key Vault resource keyVault 'Microsoft.KeyVault/vaults@2021-04-01-preview' existing = { name: keyVaultName scope: resourceGroup(keyVaultResourceGroupName) } // 为Key Vault添加访问策略 resource keyVaultAccessPolicy 'Microsoft.KeyVault/vaults/accessPolicies@2021-04-01-preview' = { // 子资源名称格式为「父资源名称/add」 name: '${keyVault.name}/add' // 将部署作用域指定为Key Vault所在的资源组 scope: resourceGroup(keyVaultResourceGroupName) properties: { accessPolicies: [ { tenantId: subscription().tenantId objectId: uamiObjectId permissions: { keys: [] secrets: ['get'] certificates: [] } } ] } dependsOn: [keyVault] }
问题原因解释
- 资源名称格式错误:嵌套资源
accessPolicies的名称不需要完整资源ID,仅需父资源名称+/add即可,完整ID会导致资源路径段数不匹配,触发第一个错误。 - 作用域设置逻辑错误:
scope不能直接加在accessPolicies资源定义的属性中,但可以为整个accessPolicies资源指定部署作用域——即Key Vault所在的资源组,因为访问策略属于Key Vault的子资源,必须在目标资源组的作用域下执行部署。 - 权限操作差异:能引用Key Vault或复制密钥属于读取操作,只需对应读取权限;而添加访问策略是写入操作,需要部署账号拥有Key Vault的
Microsoft.KeyVault/vaults/accessPolicies/write权限,且必须在目标资源组作用域下执行部署。
内容的提问来源于stack exchange,提问作者m341

