鑒于:
如https://github.com/hashicorp/terraform/issues/28727中所述,如果我們在地圖中有重復的鍵,我們會得到 NO 錯誤:
參考下面的github問題
locals {
local_dbs = {
db1 = { a = "1a" }
db1 = { a = "2a" } // notice the key here is the same as the previous (e.g. a mistake)
db3 = { a = "3a" }
}
}
output locals_map_out {
value = local.local_dbs
}
以上產生這些輸出
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
locals_map_out = {
"db1" = {
"a" = "2a"
}
"db3" = {
"a" = "3a"
}
}
注意第一個 db1 映射條目的丟失。沒有錯誤,也沒有警告。它只是默默地將第一個地圖條目替換為第二個。
github問題參考結束
我的問題是:
map使用會引發錯誤情況的重復“鍵”的替代方法是什么(外觀相似、優雅、幾行代碼) ?
前任。地圖串列 驗證碼?
locals {
local_dbs = [
{db1 = { a = "1a" }},
{db1 = { a = "2a" }}, // notice the key here is the same as the previous (e.g. a mistake)
{db3 = { a = "3a" }},
]
// code that raises error?
}
output locals_map_out {
value = local.local_dbs
}
謝謝你。
uj5u.com熱心網友回復:
TF 中沒有自定義錯誤或例外,但檢查重復項的一種方法是獲取唯一鍵串列,然后嘗試訪問最后一個元素。如果所有的鍵都是唯一的,那么操作就會成功。如果沒有,它會出錯:
locals {
local_dbs = [
{db1 = { a = "1a" }},
{db1 = { a = "2a" }}, // notice the key here is the same as the previous (e.g. a mistake)
{db3 = { a = "3a" }},
]
check_duplicatates = distinct([for v in local.local_dbs: keys(v)])[length(local.local_dbs)-1]
}
更新
output正如@MarkoE 建議的那樣:
output "check_duplicatates" {
value = local.local_dbs
#sensitive = true
precondition {
condition = length(distinct([for v in local.local_dbs: keys(v)])) == length(local.local_dbs)
error_message = "Keys in local.local_dbs are NOT unique."
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522827.html
標籤:字典地形重复钥匙
上一篇:C -根據值對映射進行排序,如果值基于鍵進行相同排序
下一篇:使用條件映射值,Pandas
