Rebecca
Rebecca

Reputation: 351

How to import existing resources to terraform in a separate subdirectory?

I have created some resources including VPC, ... in AWS using the console a long time ago and now I want to import them into Terraform. I already made a structure for my project like:

└── project_xxx
    ├── main.tf
    ├── modules
    │   ├── module_foo
    │   │   ├── main.tf
    │   │   ├── outputs.tf
    │   │   └── variables.tf
    │   ├── module_bar
    │   │   ├── main.tf
    │   │   ├── outputs.tf
    │   │   └── variables.tf
    │   ...
    ├── outputs.tf
    ├── provider.tf
    ├── README.md
    ├── terraform.tfvars
    ├── variables.tf
    └── versions.tf

but when I try to import resources in their modules, Terraform gives an Error and asks for creating them in root directory. Any suggestions?

for example: in modules/module_foo/main.tf, I have the following codes:

  resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "default"

  tags = {
    Name = "main"
  }
}

Then: in the root, I execute the following commands:

terraform init
terraform plan # it shows one resource will be added
terraform import aws_vpc.main vpc-xxx1234

Then I get the Error, that the resource must be created in root.

Upvotes: 2

Views: 4096

Answers (3)

Sadman Saadat
Sadman Saadat

Reputation: 21

I had faced the same issue. In this case, you have to create a module in the main.tf file of the root directory.

module "aws_vpc" {
  source = "./modules/module_foo"

And then import the resources using this command:

terraform import module.aws_vpc.aws_vpc.main vpc-xxx1234

Upvotes: 0

r4cc00n
r4cc00n

Reputation: 2127

I struggled with this a while ago, not exactly your use case but something similar so I will drop what I found here, perhaps it helps someone else. I would recommend using terraformer for these cases, it helps to have a good sense of your existing infrastructure and it generates a state for you, it is not bulletproof but indeed helpful https://github.com/GoogleCloudPlatform/terraformer: CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code

Upvotes: 0

Marko E
Marko E

Reputation: 18138

Since you are trying to import resources into a module, the syntax for import is slightly different compared to the case when modules are not used. In this case it should be something like:

terraform import module.module_foo.aws_vpc.main vpc-xxx1234

More information is available here: https://www.terraform.io/docs/cli/commands/import.html#example-import-into-module.

Upvotes: 3

Related Questions