Search code examples
terraformamazon-cloudfrontinfrastructure-as-code

Import aws resources into terraform module that has a for_each


I'm trying to import a couple of cloudfront distributions into terraform. As they are very similar (and can be managed together, I wanted to create 1 resource with a for_each and then import them into this resource).

The module looks like this:

variable "cloudfront_configurations" {
  default = {
    distro_1 = {
      aliases = ["url_of_distro1.com"],
    },
    distro_2 = {
      aliases = ["url_of_distro2.com"],
    },
  }
}


module "cloudfront_distribution" {
  for_each = var.cloudfront_configurations
  source  = "terraform-aws-modules/cloudfront/aws"
  version = "2.7.0"

  aliases = each.value.aliases
  ...
}

These cloudfront distro's already exist in AWS, and I wanted to import them into terraform using:

terraform import module.cloudfront_distribution[\"distro_1\"].aws_cloudfront_distribution[0] IDOFDISTRO1

This keeps giving me the error no matches found: module.cloudfront_distribution["distro_1"].aws_cloudfront_distribution[0]

Any idea what I'm doing wrong in this command?


Solution

  • After some research it appeared to be a quotation error. When referencing a module from cli, you need to quote the entire name like so:

    terraform import 'module.cloudfront_distribution["distro_1"].aws_cloudfront_distribution[0]' IDOFDISTRO1
    

    https://www.terraform.io/docs/cli/commands/import.html#example-import-into-resource-configured-with-for_each