Home > Software design >  Referencing Terraform instance attributes to user data during creation of EC2
Referencing Terraform instance attributes to user data during creation of EC2

Time:11-15

How can I pass the public_dns value of the aws_instance resource to the user_data section ?

resource "aws_instance" "app_server" {
  ami                    = "ami-04ad2567c9e3d7893"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.web-sg.name]


  user_data = <<-EOF
                  #!/bin/bash
                  sudo su
                  echo "<p> The Public DNS of instance: ${self.app_server.public_dns} </p>" >> index.html
                  python -m SimpleHTTPServer 80
                  EOF
  tags = {
    Name = "web_instance"
  }

}

I tried with self or with aws_instance.app_server.public_dns declaration but none of them worked with getting the following error.

enter image description here

enter image description here

CodePudding user response:

The public dns will become available after the instance has started. It isn't possible to reference it in user data. You can read it though with this command:

curl http://169.254.169.254/latest/meta-data/public-hostname
  • Related