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

Viewed 1077

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.

2 Answers

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

Related