My EC2 instance module configuration for us-east-1
looks as below:
module "ec2_instance" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "~> 5.2.0"
for_each = toset(["one", "two", "three"])
name = "instance-${each.key}"
ami = "ami-0f34c5ae932e6f0e4"
instance_type = "t2.micro"
key_name = "ec2keypair"
monitoring = true
vpc_security_group_ids = ["sg-0d1e7372e359bfa42"]
subnet_id = "subnet-0ff5469ab7c53e44b"
user_data = file("apache-install.sh")
tags = {
"Name" = "Modules-Demo"
Terraform = "true"
Environment = "dev"
}
}
My output looks as below:
output "ec2_publicip" {
description = "Public IP of an EC2 Instance"
value = module.ec2_instance.*.public_ip
}
This is throwing below error:
Error: Unsupported attribute on c5-outputs.tf line 8, in output "ec2_publicip": 8: value = module.ec2_instance.*.public_ip This object does not have an attribute named "public_ip".
I have gone through the documentation and public_ip
is showing as valid attribute.
You need to tell the module you want it to assign a public IP address to the instance:
module "ec2_instance" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "~> 5.2.0"
for_each = toset(["one", "two", "three"])
name = "instance-${each.key}"
ami = "ami-0f34c5ae932e6f0e4"
instance_type = "t2.micro"
key_name = "ec2keypair"
monitoring = true
vpc_security_group_ids = ["sg-0d1e7372e359bfa42"]
subnet_id = "subnet-0ff5469ab7c53e44b"
associate_public_ip_address = true # <---- add this line
user_data = file("apache-install.sh")
tags = {
"Name" = "Modules-Demo"
Terraform = "true"
Environment = "dev"
}
}
Additionally, since the module is created using for_each
, to get all of the outputs, you need to use the values
built-in function:
output "ec2_publicip" {
description = "Public IP of an EC2 Instance"
value = values(module.ec2_instance)[*].public_ip
}