HiveBrain v1.2.0
Get Started
← Back to all entries
snippetterraformCritical

How to use terraform import with module

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
withmodulehowuseimportterraform

Problem

Terraform v0.11.11

We have a quite big AWS setup created with Terraform. Different regions are applied separately, and that is why we have most of the things in modules which are imported like this:

module "assets" {
  source       = "../modules/aws-assets"
  environment  = "${var.environment}"
  upload_users = "${var.upload_users}"
}


We have one s3 bucket created manually, and I try to import it. Terraform import command does not find the configuration file and errors.

Error: resource address "aws_s3_bucket.machine-learning" does not exist in the configuration.


Before importing this resource, please create its configuration in the root module. For example:

resource "aws_s3_bucket" "machine-learning" {
  # (resource arguments)
}


terraform apply/plan do find the configuration and wants to create it which is not what we want?

Thanks for you help!

================================

Edit:

now moved configuration to root and ended up with different error...

Solution

The terraform import command uses the "Resource Address" syntax, which is a way to talk about objects in a configuration from outside of that configuration. (This is as opposed to references in the main Terraform language, which are always resolved in the context of a particular module.)

To refer to a resource that is declared in a child module, you can add a module path to the beginning of the address:

terraform import module.assets.aws_s3_bucket.machine-learning BUCKET-NAME


If you aren't sure which address to use for a particular resource instance, you can run terraform plan to see which instance address Terraform is proposing to create, and then use that same address with terraform import instead to tell Terraform to use the existing object.

For addresses that include sequences like [0] and ["foo"] to represent one of multiple instances of a module or resource, you'll need to use escaping or quoting to make sure your shell doesn't interpret those as its own metacharacters, and instead passes them on literally to Terraform:

-
On Unix-style shells, use single quotes to make the inner address be taken literally:
terraform import 'aws_instance.example["foo"]'

-
On Windows, from the command interpreter cmd.exe, escape any quotes with a backslash:

terraform import "aws_instance.example[\"foo\"]"

(PowerShell's escaping rules for external programs are very awkward and so I would not suggest using PowerShell to run a command like this.)

Code Snippets

terraform import module.assets.aws_s3_bucket.machine-learning BUCKET-NAME

Context

StackExchange DevOps Q#11358, answer score: 50

Revisions (0)

No revisions yet.