I am trying to set up an EC2 with elastic IP with terraform. I am trying to use the existing VPC and subnets for the new EC2. But Terraform is unable to recognise the existing subnet.
I am using the pre existing subnet like this -
variable "subnet_id" {}
data "aws_subnet" "my-subnet" {
id = "${var.subnet_id}"
}
When I run terraform plan I get this error -
Error: InvalidSubnetID.NotFound: The subnet ID 'subnet-02xxxxxxxxxx7' does not exist
status code: 400, request id: c4b6142b-5dfd-458c-959d-e5440b89c9fd
on ec2.tf line 3, in data "aws_subnet" "my-subnet":
3: data "aws_subnet" "my-subnet" {
This subnet was created by terraform in the past. So why does it say it doesn’t exist?
This question is also posted here -
I see 3 possible explanations for this
- The user/role you are using do not have access to the subnet
- The subnet belongs to another account
- The subnet no longer exists; it was created by Terraform but has been removed when that Terraform configuration was destroyed.
I strongly believe in separating a large deployment into smaller configurations and that means we need to share resources between configurations, as you want to do here.
But I think that using the remote state data source is a better way of doing it. When doing that, you should avoid using local state, but on AWS the S3 backend is quite good and I recommend that if you don’t use Terraform Cloud or Enterprise.
Hello Bent,
Thanks for your response. Please find my notes-
‘’’ I see 3 possible explanations for this
- The user/role you are using do not have access to the subnet
- The subnet belongs to another account
- The subnet no longer exists; it was created by Terraform but has been removed when that Terraform configuration was destroyed.’’’
The user role is Admin. So it should have access to subnet.
The subnet is in the same account.
The subnet exists. When i describe the subnet from the AWS CLI it shows the details.
I have 2 different users in my aws credentials file from 2 different accounts. I export the user i want to use before I start terraform. So the user/account should not be a problem.
Okay, so you have two different Terraform configurations in different folders and you’re using environment variables to authenticate like in the documentation?
And the provider is just the empty provider "aws" {}
in both configurations?
After you’ve exported the AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
environment variables, what is the result of terraform plan
in the configuration where you created the subnet?