Search code examples
terraformterraform-provider-awsamazon-vpc

Error creating subnet in aws_vpc with terraform


Everything seems right. What am I missing?

main.tf

provider "aws" {
region = "us-east-1"
access_key = "---"
secret_key = "---"
}

resource "aws_instance" "MyWinServer"  {
ami = "ami-085d15593174f2582"
instance_type = "t2.micro"
tags = { Name = "WinServer"  }
}
resource "aws_vpc" "MyVpc" {
cidr_block = "10.0.0.0/16"
tags = { Name = "WinVpc"  }
}

resource "aws_subnet" "MySubnet" {
vpc_id = "aws_vpc.MyVpc.id"
cidr_block = "10.0.0.0/16"
}

> terraform apply

... │ Error: error creating EC2 Subnet: InvalidVpcID.NotFound: The vpc ID 'aws_vpc.MyVpc.id' does not exist │ status code: 400, request id: 2d384c58-2d02-4761-bcd2-1044a464a844 │ │ with aws_subnet.MySubnet, │ on main.tf line 26, in resource "aws_subnet" "MySubnet": │ 26: resource "aws_subnet" "MySubnet" {

Everything seems right. What am I missing?


Solution

  • Putting comment as an answer. You have incorrect referencing for vpc_id in resource aws_subnet. You don't need string representation for vpc_id.

    The correct code would be as follows.

    resource "aws_instance" "MyWinServer" {
      ami           = "ami-085d15593174f2582"
      instance_type = "t2.micro"
      tags          = { Name = "WinServer" }
    }
    resource "aws_vpc" "MyVpc" {
      cidr_block = "10.0.0.0/16"
      tags       = { Name = "WinVpc" }
    }
    
    resource "aws_subnet" "MySubnet" {
      vpc_id     = aws_vpc.MyVpc.id ## Correction ## 
      cidr_block = "10.0.0.0/16"
    }