简体   繁体   English

如何为使用 for_each 创建的资源编写 Terraform 资源地址?

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

We have existing infrastructure in GCP and would like to import it into Terraform to have IaC.我们在 GCP 中有现有的基础设施,并希望将其导入 Terraform 以拥有 IaC。

Here is part of the Terraform file we create, the PubSub topic has existed in GCP already.这是我们创建的 Terraform 文件的一部分,PubSub 主题已经存在于 GCP 中。

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 google_pubsub_topic.pubsub_topics["aws-rds-export-s3"] aws-rds-export-s3时,显示以下错误

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.我不明白似乎是什么问题并检查了文档并尝试了不同的语法。

哦,好吧,您需要将地址用引号括起来。

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

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). Terraform 的命令行正在由您的 shell(在 Unix 系统上)或由您的 shell 和 Terraform 内部实现平台的参数解析约定(在 Windows 上)的一些逻辑的混合来解析。

For that reason, the answer is different depending on which platform and shell you are using.因此,根据您使用的平台和外壳,答案会有所不同。

  • For Windows Command Prompt:对于 Windows 命令提示符:

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

  • For PowerShell on Windows:对于 Windows 上的 PowerShell:

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

  • For typical Unix shells, like Bash:对于典型的 Unix shell,比如 Bash:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM