由于for_each,ACM证书巫婆计数= 0和aws_acm_certificate_validation失败

问题描述

我有如下代码

//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计划失败

aws_acm_certificate.livy_cert [0] .domain_validation_options中的dvo

由于索引无效0导致分析失败。我也尝试过

aws_acm_certificate.livy_cert。*。domain_validation_options中的dvo

但是,当count = 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]