How to use terraform import with passed-in variables?

I’m learning terraform, and want to setup an AWS infrastructure using the tool.

We have 3 AWS environments, sandbox, staging, and production, and have existing infrastructure to support these environments. For example, we have 3 separate VPCs for each environment.

I want to use terraform import to import the states of these resources, based on the environment I’m trying to setup. So I essentially want to do this, though I know this is not syntactically correct, but you get the idea.

$ terraform import aws_vpc.my_vpc -var 'environment=sandbox'

I therefore have my module setup like this

vpc/main.tf
-----------
provider "aws" {
  region = "us-east-1"
}
resource "aws_vpc" "my_vpc" {
  cidr_block = ""
}

vpc/variables.tf
----------------
variable "environment" {
  type map = map(string)
  default {
    sandbox    = "vpc-1234"
    staging    = "vpc-2345"
    production = "vpc-3456"
  }
}

So this means I essentially want to do

$ terraform import aws_vpc.my_vpc vpc-1234

How can I achieve this?

I don’t think you are thinking about this in the right way. Each of your environments will have its own resource. So, import the appropriate VPC into the appropriate resource.

Thanks, I’m sure I’m not. How do I “import the appropriate VPC into the appropriate resource” using Terraform script?

terraform import aws_vpc.appropriate vpc-897134

There’s NO way to program terraform so it gives me vpc-897134 if I give it -var “environment=sandbox” for example? I realize I can program the vars in my .bashrc file, and do

$ terraform import aws_vpc.appropriate $sandbox_vpc

but I’m asking if I can stay purely in terraform to get the info.

Hi @ZillaG,

The terraform import command is indeed the mechanism by which we tell Terraform that aws_vpc.appropriate corresponds with vpc-897134. Terraform tracks the relationship between remote objects and local resource instances in snapshots of the Terraform State, so IDs like this generally do not appear in the configuration at all in common usage.

You can think of terraform import as a way to preempt Terraform’s default behavior of creating a new remote object when it encounters a resource that it hasn’t seen before. terraform import means “pretend you created this”, and is an imperative command rather than something driven by configuration because it’s a step you should run only once during initial bootstrapping, with Terraform then taking ownership of that object for all future changes via terraform apply.