Terraform - A managed resource has not been declared in the root module

Viewed 58816

i'm trying create ec2 instance and setup load balancer using terraform but i'm facing follwing error. How to create instance and configure load balacer in a single main.tf file?

Error: Reference to undeclared resource

"aws_lb_target_group" "front-end":27: vpc_id = "${aws_vpc.terrafom-elb.id}" A managed resource "aws_vpc" "terrafom-elb" has not been declared in the root module.source`

code:

  region = "us-east-1"
  access_key = "*********************"
  secret_key = "**********************"
}

resource "aws_instance" "terraform" {
  ami           = "ami-07ebfd5b3428b6f4d"
  instance_type = "t2.micro"
  security_groups    = ["nodejs","default"]
  tags = {
    Name = "terrafom-elb"
  }
}

resource "aws_lb" "front-end"{
  name = "front-end-lb"
  internal = false
  security_groups    = ["nodejs"]

}

resource "aws_lb_target_group" "front-end" {
  name     = "front-end"
  port     = 8989
  protocol = "HTTP"
  vpc_id   = "${aws_vpc.terrafom-elb.id}"
  depends_on = [aws_instance.terraform]
}
2 Answers

You can add a data structure to the top and pass VPC ID as variable:

data "aws_vpc" "selected" {
  id = var.vpc_id
}

And reference it as vpc_id = data.aws_vpc.selected.id

There's a typo where you're assigning the vpc_id:

vpc_id   = "${aws_vpc.terrafom-elb.id}"

should be:

vpc_id   = "${aws_vpc.terraform-elb.id}"

note the missing 'r' in the word 'terraform'

Related