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
相关产品推荐
相关产品推荐

