我创建了一个基本的 terraform 模块,它创建一个
aws_route53_zone
资源,如果 subject_alternative_names
填充在输入地图中,它将创建一个 aws_acm_certificate
及其相应的 zone
。创建证书后,它将使用 aws_route53_record
资源的返回值创建一个 aws_acm_certificate
cname 资源,以填充记录 name
、type
和 records
。我能够成功创建aws_route53_zone
和aws_acm_certificate
。但是,我在尝试创建 aws_route53_record
时遇到以下错误。我错过了什么?或者什么是达到预期结果的正确方法?
错误片段
│ Error: Invalid index
│
│ on main.tf line 34, in resource "aws_route53_record" "cname":
│ 34: type = aws_acm_certificate.cert[each.key].domain_validation_options[0].resource_record_type
│ ├────────────────
│ │ aws_acm_certificate.cert is object with 2 attributes
│ │ each.key is "example.com"
│
│ Elements of a set are identified only by their value and don't have any
│ separate index or key to select with, so it's only possible to perform
│ operations across all elements of the set.
输入
module "test123" {
source = "./test123"
zone_maps = {
"example.com" = {
subject_alternative_names = ["sub.example.com", "api.example.com"]
}
"test.com" = {
subject_alternative_names = ["sub.test.com"]
}
}
tags = { SomeTag = "SomeTag" }
}
main.tf
resource "aws_route53_zone" "zone" {
for_each = var.zone_maps
name = each.key
}
resource "aws_acm_certificate" "cert" {
for_each = { for k, v in var.zone_maps : k => v if v.subject_alternative_names != null }
domain_name = each.key
subject_alternative_names = each.value.subject_alternative_names
validation_method = "DNS"
lifecycle {
create_before_destroy = true
}
tags = var.tags
}
resource "aws_route53_record" "cname" {
for_each = { for k, v in aws_acm_certificate.cert : k => v }
zone_id = aws_route53_zone.zone[each.key].zone_id
ttl = 300
name = aws_acm_certificate.cert[each.key].domain_validation_options[0].resource_record_name
type = aws_acm_certificate.cert[each.key].domain_validation_options[0].resource_record_type
records = [aws_acm_certificate.cert[each.key].domain_validation_options[0].resource_record_name]
depends_on = [
aws_acm_certificate.cert
]
}
变量.tf
variable "region" {
description = "The region to deploy."
type = string
default = "us-east-1"
}
variable "zone_maps" {
description = "A map of zones. SAN (optional)"
type = map(object({
subject_alternative_names = optional(list(string))
}))
}
variable "tags" {
description = "Tags"
type = map(any)
default = {}
}
版本.tf
terraform {
required_version = ">= 0.13"
required_providers {
aws = ">=3.5.0"
}
experiments = [module_variable_optional_attrs]
}
provider "aws" {
region = var.region
}