Terraform:实例模块列表对象输出传递至Route53模块遇错求助
问题根源与解决方案
核心问题分析
- 双重Count导致模块实例冗余:main.tf中给
instance模块添加了count = length(var.instances),同时模块内部的aws_instance又用了相同的count,会创建N*N个实例,且module.instance变成列表类型,无法直接访问.host_ips属性。 - 拼写错误:实例模块输出中把
public_ip写成了pubic_ip,后续Route53模块调用时会出现属性不存在的问题。 - 变量类型约束缺失:Route53模块的
host_ips变量未明确类型,Terraform无法正确推断结构。
具体修改步骤
1. 修正main.tf中的模块调用
去掉instance模块的count,让模块内部统一处理所有实例:
module "instance" { source = "./instance" instances = var.instances sgs = module.security.sgs } module "route_53" { source = "./route_53" host_ips = module.instance.host_ips }
2. 修正instance/instance.tf的输出
修复public_ip拼写错误,并添加类型约束:
resource "aws_instance" "linux" { ami = var.machine_image[var.instances[count.index].distro].ami count = length(var.instances) instance_type = var.instances[count.index].instance_type monitoring = false vpc_security_group_ids = [ for sg in var.instances[count.index].security_groups: var.sgs[sg] ] associate_public_ip_address = true source_dest_check = true disable_api_termination = false root_block_device { volume_type = "gp2" volume_size = var.instances[count.index].volume_size delete_on_termination = false } tags = { "Name" = var.instances[count.index].hostname } } output "host_ips" { value = [ for hip in aws_instance.linux: { hostname = hip.tags["Name"] public_ip = hip.public_ip } ] type = list(object({ hostname = string public_ip = string })) }
3. 完善route53/variables.tf的类型约束
明确host_ips的结构类型:
variable "instances" { default = "The nova.json instances" } variable "host_ips" { type = list(object({ hostname = string public_ip = string })) description = "FQDNs & Public facing IP addresses from Instances" }
4. 修正route53/record.tf的属性调用
同步修复public_ip的拼写:
resource "aws_route53_record" "public" { count = length(var.host_ips) name = var.host_ips[count.index].hostname records = [ var.host_ips[count.index].public_ip ] ttl = 300 type = "A" zone_id = aws_route53_zone.public_zone.zone_id allow_overwrite = true }
原理说明
- 去掉
instance模块的count后,module.instance变成单个模块对象,可直接访问其host_ips输出(该输出是所有实例的列表)。 - 明确类型约束后,Terraform能提前验证数据结构,避免运行时错误。
- 修复拼写错误确保属性能正确映射。
内容的提问来源于stack exchange,提问作者LinuxGuru
相关产品推荐
相关产品推荐

