Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to display Public DNS when using aws ec2_instance module

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading