I created a variable.tf file and adding the below VPC and Subnet codes.
variable "VPC_ID" {
description = "This is VPC created using variables and not as hard coded information."
type = string
default = "My-VPC"
}
variable "cidr" {
description = "Setting up with the IPv4 CIDR blocks which can be used for this testing project."
type = string
default = "10.0.0.0/16"
}
variable "Public_Subnet" {
description = "Creating an Ip4 Public Subnet."
type = list(string)
default = ["10.0.1.0/24"]
}
variable "Public_AVZ" {
description = "This needs to be used for public availability zone only."
type = string
default = "aps1-az1"
}
I then created 2 seperate .tf files for VPC and Subnet and added the below codes into it.
resource "aws_vpc" "My-VPC" {
cidr_block = var.cidr
instance_tenancy = var.Instance_tenancy
tags = {
Name = var.VPC_ID
}
}
resource "aws_subnet" "Public_Subnet" {
vpc_id = var.VPC_ID
cidr_block = var.cidr
}
Now when I run the validate and plan commands, it does not show any error and shows all correct. However, when I run the apply command, I get the below error.
Error: creating EC2 Subnet: InvalidVpcID.NotFound: The vpc ID ‘My_VPC’ does not exist
│ status code: 400, request id: 5d6d19ed-2067-4653-8611-c6fdc48b24f4
│
│ with aws_subnet.Public_Subnet,
│ on subnets.tf line 3, in resource "aws_subnet" "Public_Subnet":
│ 3: resource "aws_subnet" "Public_Subnet" {
│
Tried few blogs and tweaked the setting, but with no luck.
2
Answers
VPC ID is not something you define the value for. It is provided after the VPC resource is created. The VPC ID is in the following format:
You can find it in the AWS console:
Since you are using terraform, you can use the implicit reference:
The name you are assigning the VPC is not the VPC’s ID, it is just a name. You should probably rename the variable to something like
VPC_NAME
.The VPC’s ID is an ID that AWS assigns to your VPC at the time it is created. It is available in Terraform as an attribute of the VPC resource.
Your subnets needs to reference the ID attribute of the VPC resource, like this: