You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform:如何获取容器非空identity的首个元素,否则返回null

解决Terraform中identity为空列表时的取值问题

当azurerm_container_registry的identity字段为空列表时,直接使用identity[0].principal_id会触发索引无效报错,具体报错信息如下:

Error: Invalid index
on .../outputs.tf line 21, in output "container_registry_primary_identity_principal_id":
21: value = azurerm_container_registry..identity[0].principal_id
├────────────────
│ azurerm_container_registry.
.identity is empty list of object
The given key does not identify an element in this collection value: the
collection has no elements.

要实现identity非空时取首个元素的principal_id,为空时返回null,可以用以下两种方法:

  • 方法一:使用try函数
    try函数会尝试执行第一个表达式,若执行失败则返回第二个值,代码写法简洁:

    value = try(azurerm_container_registry.***.identity[0].principal_id, null)
    
  • 方法二:通过长度判断实现条件取值
    先判断identity列表的长度是否大于0,再决定取值逻辑:

    value = length(azurerm_container_registry.***.identity) > 0 ? azurerm_container_registry.***.identity[0].principal_id : null
    

两种方法都能避免空列表索引报错,优先推荐try函数的写法。

内容的提问来源于stack exchange,提问作者Nick Vee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:15:57