如何在terrafrom变量中存储GCP服务帐户JSON?

时间:2020-06-20 20:08:51

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

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

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

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

2 个答案:

答案 0 :(得分:3)

您可以在Terraform Cloud用户界面中以名为{strong> google_credentials 的Multi-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

答案 1 :(得分:0)

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

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