Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 735
Chris F Avatar asked Jan 23 '26 01:01

Chris F


1 Answers

I had the same issue and figured out that the order is important. This command works:

$ terraform import -var 'environment=sandbox' aws_vpc.my_vpc vpc-1234
like image 82
DomZach Avatar answered Jan 25 '26 20:01

DomZach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!