4
votes

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
There is indeed no aws_vpc resource in this config. Can you share the rest of your config that contains it?Matt Schuchard
or maybe is it a data source that you want to use ? in that case you may use data.aws_vpc.terraform_elb instead. if not, Matt is right, the rest of the config is needed to understand the issuenulse

2 Answers

5
votes

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

2
votes

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'