[英]Terraform create either one block type or another within a resource
我正在嘗試使用 Terraform 在 GCP 中創建警報策略,並且基於 boolean 值我想選擇是創建 condition_threshold 還是 conditionAbsent 類型的策略。 由於這些都是 google_monitoring_alert_policy 中的不同類型的塊,我無法找到一種方法來根據 boolean 值創建一個或另一個。
resource "google_monitoring_alert_policy" "logging_alert_policy" {
for_each = local.metrics_map
project = var.project
display_name = lower(format("%s%s%s%s", join("_", [element(split("-", each.value.appcode), length(split("-", each.value.appcode)) - 1), element(split("-", each.value.appcode), 0)]), " ", "log_match ", each.value.display_name))
combiner = each.value.how_to_trigger
dynamic "conditions" {
for_each = each.value.conditions
content {
display_name = lower(format("%s%s%s%s", join("_", [element(split("-", conditions.value.appcode), length(split("-", conditions.value.appcode)) - 1), element(split("-", conditions.value.appcode), 0)]), " ", "log_match ", conditions.value.display_name))
# condition_threshold {
# filter = lower("metric.type=\"logging.googleapis.com/user/${format("%s%s%s%s", conditions.value.appcode, "-", lower(replace(lookup(conditions.value, "metric_name"), "/\\W|_|\\s/", "-")), "")}\" resource.type=\"${conditions.value.resource_type}\"")
# comparison = conditions.value.comparison
# threshold_value = conditions.value.threshold_value
# duration = conditions.value.duration
# trigger {
# count = lookup(conditions.value, "trigger_count", var.default_metric_alert["trigger_count"])
# }
# aggregations {
# alignment_period = conditions.value.alignment_period
# per_series_aligner = conditions.value.per_series_aligner
# cross_series_reducer = conditions.value.cross_series_reducer
# group_by_fields = conditions.value.group_by_fields
# }
# }
condition_absent {
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_MAX"
cross_series_reducer = "REDUCE_MAX"
group_by_fields = ["resource.label.container_name"]
}
trigger {
count = 1
}
duration = "180s"
filter = lower("metric.type=\"logging.googleapis.com/user/${format("%s%s%s%s", conditions.value.appcode, "-", lower(replace(lookup(conditions.value, "metric_name"), "/\\W|_|\\s/", "-")), "")}\" resource.type=\"${conditions.value.resource_type}\"")
}
}
}
我會建議嵌套的動態塊依賴於一個元素的local
計算集 - 或者沒有元素。
這個想法的簡短例子:
locals {
absent = false # let's say we want to have "condition_threshold" block if this is true
conditions_config = local.absent == false ? ["1"] : []
absent_conditions_config = local.absent == true ? ["1"] : []
# I agree the above code is ugly but shows exactly the idea
}
# [...]
dynamic "conditions" {
for_each = each.value.conditions
content {
#[...]
dynamic "condition_threshold" {
for_each = toset(local.conditions_config) # this will be one element if local.absent = false
# content { ... }
}
dynamic "condition_absent" {
for_each = toset(local.absent_conditions_config) # this will be one element if local.absent = true
# content { ... }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.