使用Terraform分配Cosmos DB默认读写角色报错,Azure CLI可正常执行
问题解决:Terraform分配Cosmos DB默认读写角色报错
问题原因
Terraform的azurerm_cosmosdb_sql_role_assignment资源要求role_definition_id必须是完整的Azure资源ID,而非仅默认角色的GUID。Azure CLI能正常执行是因为它会自动根据传入的账户信息拼接完整的角色定义ID,但Terraform不会做这个自动补全,直接传入GUID会触发解析错误。
解决方案
你可以通过以下两种方式修正代码:
方法1:手动拼接完整角色定义ID
直接基于Cosmos DB账户ID拼接默认角色的完整路径:
resource "azurerm_cosmosdb_sql_role_assignment" "example" { resource_group_name = data.azurerm_cosmosdb_account.profiles_cdb.resource_group_name account_name = data.azurerm_cosmosdb_account.profiles_cdb.name # 拼接完整的角色定义ID role_definition_id = "${data.azurerm_cosmosdb_account.profiles_cdb.id}/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002" principal_id = azurerm_linux_function_app.syringe_function_app.identity[0].principal_id scope = data.azurerm_cosmosdb_account.profiles_cdb.id }
方法2:通过数据源获取完整角色定义ID(推荐)
使用azurerm_cosmosdb_sql_role_definition数据源查询默认角色的完整ID,避免硬编码路径,适配不同环境:
# 查询Cosmos DB默认读写角色的完整ID data "azurerm_cosmosdb_sql_role_definition" "cosmos_read_write" { resource_group_name = data.azurerm_cosmosdb_account.profiles_cdb.resource_group_name account_name = data.azurerm_cosmosdb_account.profiles_cdb.name name = "Cosmos DB Built-in Data Contributor" # 默认读写角色的名称 } resource "azurerm_cosmosdb_sql_role_assignment" "example" { resource_group_name = data.azurerm_cosmosdb_account.profiles_cdb.resource_group_name account_name = data.azurerm_cosmosdb_account.profiles_cdb.name role_definition_id = data.azurerm_cosmosdb_sql_role_definition.cosmos_read_write.id principal_id = azurerm_linux_function_app.syringe_function_app.identity[0].principal_id scope = data.azurerm_cosmosdb_account.profiles_cdb.id }
验证说明
修改后执行terraform apply,即可成功完成角色分配,效果与Azure CLI执行的操作一致。
内容的提问来源于stack exchange,提问作者michasaucer
相关产品推荐
相关产品推荐

