A managed resource “aws_subnet” “pubsubnet” has not been declared in the root module.

Hi Techies,

We are going to see how to resolve ‘A managed resource “aws_subnet” “pubsubnet” has not been declared in the root module.’  error while using terraform to create 2 EC2 instance with VPC in AWS

code:

resource "aws_instance" "pub_instance" {
ami = "ami-033fabdd332044f06"
instance_type = "t2.micro"
availability_zone = "us-east-2a"
associate_public_ip_address = "true"
vpc_security_group_ids = [aws_security_group.PUBSG.id]
subnet_id = aws_subnet.pubsubnet.id
key_name = "Terraform_Srv"

tags = {
Name = "WEBSERVER"
}

}

resource "aws_instance" "pvt_instance" {
ami = "ami-033fabdd332044f06"
instance_type = "t2.micro"
availability_zone = "us-east-2b"
associate_public_ip_address = "true"
vpc_security_group_ids = [aws_security_group.PVTSG.id]
subnet_id = aws_subnet.pvtsubnet.id
key_name = "Terraform_Srv"

tags = {
Name = "APPSERVER"
}

Error:

[root@ip-172-31-7-226 terraform]# terraform apply
╷
│ Error: Reference to undeclared resource
│
│ on main.tf line 163, in resource "aws_instance" "pub_instance":
│ 163: subnet_id = aws_subnet.pubsubnet.id
│
│ A managed resource "aws_subnet" "pubsubnet" has not been declared in the root module.
╵
╷
│ Error: Reference to undeclared resource
│
│ on main.tf line 178, in resource "aws_instance" "pvt_instance":
│ 178: subnet_id = aws_subnet.pvtsubnet.id
│
│ A managed resource "aws_subnet" "pvtsubnet" has not been declared in the root module.

After checking the full code of script, found that I have declared the names like PUBSUB & PVTSUB for public and private subnet wiseversa.

But I wrongly mentioned like pubsubnet & pvtsubnet in the EC2 instance creation. So, after renaming it to correctly like below it is fixed.

subnet_id = aws_subnet.pubsubnet.id
subnet_id = aws_subnet.pubsubnet.id

modified like below based on the declared name inn previous code

subnet_id = aws_subnet.PUBSUB.id
subnet_id = aws_subnet.PVTSUB.id

Result:

After changing the error was fixed and find the below result

aws_instance.pvt_instance: Creating...
aws_instance.pub_instance: Creating...
aws_route_table.PVTRT: Modifying... [id=rtb-05ab30d4598210e59]
aws_route_table.PVTRT: Modifications complete after 0s [id=rtb-05ab30d4598210e59]
aws_instance.pub_instance: Still creating... [10s elapsed]
aws_instance.pvt_instance: Still creating... [10s elapsed]
aws_instance.pvt_instance: Still creating... [20s elapsed]
aws_instance.pub_instance: Still creating... [20s elapsed]
aws_instance.pub_instance: Still creating... [30s elapsed]
aws_instance.pvt_instance: Still creating... [30s elapsed]
aws_instance.pvt_instance: Creation complete after 31s [id=i-096c28fbbaeff8a42]
aws_instance.pub_instance: Creation complete after 31s [id=i-0f745c3aeca6327aa]

Apply complete! Resources: 2 added, 1 changed, 0 destroyed.
[root@ip-172-31-7-226 terraform]#