本地创建Terraform模块引用VPC资源时遇属性不支持错误求助
问题:Terraform模块引用VPC资源时出现Unsupported attribute错误
本地创建Terraform模块,在EC2实例和安全组模块中引用VPC相关资源时无法推进,报错提示module.vpc不存在vpc_id属性。以下是相关代码及错误信息:
EC2模块代码
data "aws_ami" "ubuntu" { owners = ["373042721571"] most_recent = true filter { name = "name" values = ["image-test"] } } # data "template_file" "user_data" { # template = file("userdata.sh") # } resource "aws_instance" "web-1" { count = 1 ami = "${data.aws_ami.ubuntu.id}" instance_type = "t2.micro" key_name = var.key_name subnet_id = var.subnetid vpc_security_group_ids = var.securitygroupid associate_public_ip_address = true # user_data = data.template_file.user_data.rendered tags = { Name = "Server-1" Owner = "Terraform" } }
安全组模块代码
resource "aws_security_group" "allow_all" { name = var.sg_name description = "allowing all traffic to the servers in public " vpc_id = var.vpcid ingress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } tags = { Name = "allow_all_trafic" } }
根模块调用代码
module "vpc" { source = "./module/vpc" vpc_cidr = var.vpc_cidr vpc_name = var.vpc_name IGW_name = var.IGW_name routing_table_public_name = var.routing_table_public_name } module "securitygroup" { source = "./module/securitygroup" sg_name = var.sg_name vpcid = module.vpc.vpc_id } module "ec2" { source = "./module/ec2" key_name = var.key_name securitygroupid = module.securitygroup.aws_security_group.allow_all.id subnetid = module.vpcmodule.public[0] }
错误信息
│ Error: Unsupported attribute
│
│ on output.tf line 3, in output "vpc_id":
│ 3: value = module.vpc.vpc_id
│ ├────────────────
│ │ module.vpc is a object, known only after apply
│
│ This object does not have an attribute named "vpc_id".
解决方案
给VPC模块添加输出配置
报错核心是VPC模块未导出vpc_id等属性,需在VPC模块目录下创建outputs.tf,显式导出所需资源属性:output "vpc_id" { description = "ID of the created VPC" value = aws_vpc.your_vpc_resource.id # 替换为VPC模块中实际的aws_vpc资源名称 } output "public_subnets" { description = "List of public subnet IDs" value = aws_subnet.public_subnets.*.id # 替换为VPC模块中实际的公网子网资源名称 }修正根模块的子网引用错误
根模块中EC2的subnetid = module.vpcmodule.public[0]属于拼写错误,应改为:subnetid = module.vpc.public_subnets[0]修正安全组ID的传递方式
EC2的vpc_security_group_ids要求传入列表类型,需先在安全组模块添加输出:# 安全组模块的outputs.tf output "sg_id" { description = "ID of the created security group" value = aws_security_group.allow_all.id }再在根模块调用EC2时用列表传递:
module "ec2" { # ...其他参数 securitygroupid = [module.securitygroup.sg_id] }验证模块输出
运行terraform plan前,确保所有模块的输出配置正确,Terraform能识别到导出的属性。
内容的提问来源于stack exchange,提问作者gcn
相关产品推荐
相关产品推荐

