【问题标题】:How to store GCP Service Account JSON in a terrafrom variable?如何将 GCP 服务帐户 JSON 存储在 terraform 变量中?
【发布时间】:2020-10-10 22:30:48
【问题描述】:

我的 terraform gcp 提供程序配置看起来像

provider "google" {
  project     = var.project
  region      = var.region
  credentials = file("account.json")
}

我想在 terraform cloud 上运行我的 terraform 文件,我不想将 account.json 文件放在源代码管理中。如何将 json GCP 服务帐户文件存储在 terraform cloud 中,然后从 terraform 脚本访问它?

【问题讨论】:

标签: terraform terraform-provider-gcp terraform-cloud


【解决方案1】:

您可以在 Terraform Cloud UI 中以名为 google_credentialsMulti-Line value 的形式提供凭据,并将其标记为 Sensitive Value,然后为您的帐户输入正确的值(可能只是您已经拥有的 account.json 文件的复制粘贴):

{
  "type": "service_account",
  "project_id": "project-id",
  "private_key_id": "key-id",
  "private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
  "client_email": "service-account-email",
  "client_id": "client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
}

然后,您可以将工作空间变量中的凭据提供给 Terraform 模块中的 google 提供程序,如下所示作为将被解释为 JSON 的单个变量:

provider "google" {
  project     = var.project
  region      = var.region
  credentials = var.google_credentials
}

variable "google_credentials" {
  description = "the contents of a service account key file in JSON format."
  type = string
}

凭据 -(可选)JSON 格式的服务帐户密钥文件的路径或内容。您可以使用 Cloud Console 管理密钥文件。

来自Google Provider Configuration Reference

【讨论】:

  • 如果你在 terraform cloud 之外运行它,是否有一种特殊的语法可以在 .tfvars 中设置多行变量,如何让 .tf 在本地机器和 terraform cloud 上工作
  • 在本地运行时最好提供 account.json 的路径。多行 tfvars 值很尴尬。这也行。terraform apply -var='google_credentials="/absolute/path/to/account.json"
  • @ams 请接受我的回答,因为它解决了您的问题。如果您发布并链接到其他问题,我很乐意回复。
  • @AlainO'Dea :我试过了,看起来直接复制粘贴 JSON 不起作用。你测试过这个吗?
  • @Prashant 是的。我在生产中使用了未修改的代码。我在 7 月 21 日的评论中解决了在本地使用多行变量的风险。像这样提供 JSON 特别尴尬,我建议改为提供文件。请尝试一下。
【解决方案2】:

更好的答案是通过运行删除服务帐户密钥文件中的换行符

tr -d '\n' < current_service_key.json > no_new_line_key.json

将“no_new_line_key.json”的内容粘贴到 Terraform Cloud 的变量部分,并使用此处记录的任何变量名称,例如 GOOGLE_CREDENTIALS 或 GOOGLE_CLOUD_KEYFILE_JSON:(https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference)。我使用了 GOOGLE_CREDENTIALS

Screenshot of the configuration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2021-05-18
    • 1970-01-01
    • 2022-01-24
    • 2020-07-15
    • 2020-06-08
    • 2021-04-06
    • 2021-12-02
    相关资源
    最近更新 更多