Request for feedback: for_each in import blocks

Today we launched our first Alpha release for the Terraform 1.7 series: 1.7.0-alpha20231025. Terraform v1.7 adds the ability to use for_each inside import blocks.

A simple mapping of import IDs might look like so:

import {
  for_each = {
    "staging" = "bucket1"
    "uat"     = "bucket2"
    "prod"    = "bucket3"
  }
  to = aws_s3_bucket.this[each.key]
  id = each.value
}

A resource using count can be indexed via numeric values, or an ordered collection can be used in the for_each expression:

import {
  for_each = ["bucket1", "bucket2", "bucket3"]
  to = aws_s3_bucket.this[each.key]
  id = each.value
}

And in the case of expanded modules, more complex structures can be built to accomplish the mapping:

locals {
  bucket_ids = [
    { 
      group = "one"
      key   = "bucket1"
      id    = "one_1"
    },
    {
      group = "one"
      key   = "bucket2"
      id    = "one_2"
    },
    {
      group = "two"
      key   = "bucket1"
      id    = "two_1"
    },
    {
      group = "one"
      key   = "bucket2"
      id    = "two_2"
    },
  ]
}

import {
  for_each = local.bucket_ids
  id = each.value.id
  to = module.group[each.value.group].aws_s3_bucket.this[each.value.key]
}

The for_each expression must result in an object or collection value wholly known during the plan - if this is not the case, Terraform should provide a helpful error.

Currently for_each cannot be used in combination with config generation during import. A resource block must be present in config for the target resource.

How to provide feedback

Please feel free to post questions, comments, and other feedback here. If you discover a bug or usability issue, we would be grateful if you could open a GitHub issue at Issues · hashicorp/terraform · GitHub.

Thanks!