替换地图中的单个值

0 terraform

我有这样的地图,需要在本地分配resource_id_tomonitor。因为地图位于我的 tfvars 文件中,而 locals 位于我的 main.tf 文件中

alerts_settings = {
    alert1 = {
    alert_name = "My First Alert"
    resource_group_name  = "my-rg"
    alert_criteria_settings = [
        {
        metric_namespace = "Microsoft.Network/networkWatchers/connectionMonitors"
        metric_name = "ChecksFailedPercent"
        metric_aggregation = "Average"
        metric_operator = "GreaterThanOrEqual"
        metric_threshold = "50.0"
        }
    ]
    resource_id_tomonitor = [] # to be replaced at runtime
    alert_description   = "from POC One fo the VM is Down but THis is not high priotiry as we have multiple VM serving Traffic"
    action_group_name     =   "POC-Monitor-AG"
    severity = 3
    },
        alert2 = {
    alert_name = "My Second Alert"
    resource_group_name  = "my-rg"
    alert_criteria_settings = [
        {
        metric_namespace = "Microsoft.Network/networkWatchers/connectionMonitors"
        metric_name = "ChecksFailedPercent"
        metric_aggregation = "Average"
        metric_operator = "GreaterThanOrEqual"
        metric_threshold = "100.0"
        }
    ]
    resource_id_tomonitor = [] # to be replaced at runtime
    alert_description   = "BOTH POC VM are Down. THis is HIGH priotiry P1 Issue"
    action_group_name     =   "POC-Monitor-AG"
    severity = 0
    },
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做类似的事情

locals {
    var.alerts_settings["alert1"].resource_id_tomonitor="hello world"
    var.alerts_settings["alert2"].resource_id_tomonitor="hello world2"
}
Run Code Online (Sandbox Code Playgroud)

The*_*erk 5

您可以使用for 表达式查找函数来完成此操作

locals {
  alerts_settings = {
    alert1 = {
      alert_name            = "VM1 Down"
      resource_id_tomonitor = ""
    }
    alert2 = {
      alert_name            = "VM2 Down"
      resource_id_tomonitor = ""
    }
  }

  new_values = {
    alert1 = "hello world"
    alert2 = "hello world 2"
  }
}

output "updated" {
  value = { for k, a in local.alerts_settings : k => {
    alert_name            = a.alert_name
    resource_id_tomonitor = lookup(local.new_values, k, a.resource_id_tomonitor)
  } }
}
Run Code Online (Sandbox Code Playgroud)

这使:

Changes to Outputs:
  + updated = {
      + alert1 = {
          + alert_name            = "VM1 Down"
          + resource_id_tomonitor = "hello world"
        }
      + alert2 = {
          + alert_name            = "VM2 Down"
          + resource_id_tomonitor = "hello world 2"
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新

为了仅替换键的子集,您可以将原始映射与包含更新的映射合并。

output "updated" {
  value = { for k, a in local.alerts_settings : k => merge(a, {
    resource_id_tomonitor = lookup(local.new_values, k, a.resource_id_tomonitor)
  }) }
}
Run Code Online (Sandbox Code Playgroud)