ACM 证书 count=0 & aws_acm_certificate_validation 由于 for_each 而失败

ACM Certificate witch count=0 & aws_acm_certificate_validation fails due to for_each

我有如下代码

//Create acm certificate for livy_cert
resource "aws_acm_certificate" "livy_cert" {
  count = local.count
  domain_name       = "${var.subsystem}-${var.component}-livy.${var.region_fqdn}"
  validation_method = "DNS"

  lifecycle {
    create_before_destroy = true
  }
}

//Validation route53
resource "aws_route53_record" "certificate_validation" {
  for_each = {
    for dvo in aws_acm_certificate.livy_cert[0].domain_validation_options : dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    }
  }
  name    = each.value.name
  records = [each.value.record]
  ttl     = 60
  type    = each.value.type
  zone_id = module.core_info.route53_zone_id
}

//Validate certificate before assigning
resource "aws_acm_certificate_validation" "livy_alb_validation_cert" {
  count                   = local.count
  certificate_arn         = aws_acm_certificate.livy_cert[0].arn
  validation_record_fqdns = [for record in aws_route53_record.certificate_validation : record.fqdn]
}

如您所见,我的证书带有 count 变量,但是当我的 count =0 时 terraform 计划失败

for dvo in aws_acm_certificate.livy_cert[0].domain_validation_options

由于 0 索引无效而无法解析。我也试过

for dvo in aws_acm_certificate.livy_cert.*.domain_validation_options

但是,当计数 =1

时,这也会失败

知道如何修复它吗?

您可以 flatten domain_validation_options 的列表,然后再遍历它:

// Create acm certificate for livy_cert
resource "aws_acm_certificate" "livy_cert" {
  count = local.count
  domain_name       = "${var.subsystem}-${var.component}-livy.${var.region_fqdn}"
  validation_method = "DNS"

  lifecycle {
    create_before_destroy = true
  }
}

// Validation route53
resource "aws_route53_record" "certificate_validation" {
  for_each = {
    for dvo in flatten([
      for cert in aws_acm_certificate.livy_cert: cert.domain_validation_options
    ]): dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    }
  }

  name    = each.value.name
  records = [each.value.record]
  ttl     = 60
  type    = each.value.type
  zone_id = module.core_info.route53_zone_id
}

// Validate certificate before assigning
resource "aws_acm_certificate_validation" "livy_alb_validation_cert" {
  count                   = local.count
  certificate_arn         = aws_acm_certificate.livy_cert[count.index].arn
  validation_record_fqdns = [for record in aws_route53_record.certificate_validation : record.fqdn]
}

(注意,对于livy_alb_validation_cert,我使用livy_cert[count.index]而不是livy_cert[0],只是为了整洁)