How to write the Terraform resource address for resource created with for_each?

730 Views Asked by At

We have existing infrastructure in GCP and would like to import it into Terraform to have IaC.

Here is part of the Terraform file we create, the PubSub topic has existed in GCP already.

locals {
    gcp_pubsub_topics = [
        "aws-rds-export-s3"
    ]
}

resource "google_pubsub_topic" "pubsub_topics" {
    for_each = toset(local.gcp_pubsub_topics)

    project = var.gcp_target_project_id
    name = each.value

    labels = {
        env = terraform.workspace
    }
}

When I run terraform import google_pubsub_topic.pubsub_topics["aws-rds-export-s3"] aws-rds-export-s3, the following error shown

terraform import $(./var.sh) google_pubsub_topic.pubsub_topics["aws-rds-export-s3"] aws-rds-export-s3 
╷
│ Error: Index value required
│ 
│   on <import-address> line 1:
│    1: google_pubsub_topic.pubsub_topics[aws-rds-export-s3]
│ 
│ Index brackets must contain either a literal number or a literal string.
╵

For information on valid syntax, see:
https://www.terraform.io/docs/cli/state/resource-addressing.html

I do not understand what seems to be the problemm and checked the doc and tried different syntax.

2

There are 2 best solutions below

1
On

Oh well, you need to wrap the address in quote.

terraform import $(./var.sh) 'google_pubsub_topic.pubsub_topics["aws-rds-export-s3"]' aws-rds-export-s3
0
On

The command line for Terraform is being parsed either by your shell (on Unix systems) or by a mixture of your shell and some logic inside Terraform that implements the platform's argument parsing conventions (on Windows).

For that reason, the answer is different depending on which platform and shell you are using.

  • For Windows Command Prompt:

    terraform import google_pubsub_topic.pubsub_topics[\"aws-rds-export-s3\"] aws-rds-export-s3

  • For PowerShell on Windows:

    terraform import --% google_pubsub_topic.pubsub_topics[\"aws-rds-export-s3\"] aws-rds-export-s3

  • For typical Unix shells, like Bash:

    terraform import 'google_pubsub_topic.pubsub_topics["aws-rds-export-s3"]' aws-rds-export-s3