如何使用Terraform获取默认的GCP项目和区域?

时间:2020-09-30 09:01:02

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

对于标准tf样板:

provider "google" {}

如何获取提供商的默认projectregion?类似于AWS中的aws_region(例如this question),但类似于Google Compute Engine(GCE / GCP)。

在某些情况下,这些是在环境变量中外部指定的:

export GOOGLE_PROJECT=myproject
export GOOGLE_REGION=europe-west2
terraform apply

很少用hcl代码覆盖它们:

provider "google" {
  project = "myproject"
  region  = "europe-west2"
}

此操作失败,并显示A managed resource "provider" "google" has not been declared in the root module.

output "region" {
  value = provider.google.region
}

1 个答案:

答案 0 :(得分:1)

基本

使用google_client_config数据源:

data "google_client_config" "this" {}

output "region" {
  value = data.google_client_config.this.region
}

output "project" {
  value = data.google_client_config.this.project
}

多个提供商

这甚至可以用于多个提供商:

provider "google" {
  region = "europe-west2"
}

provider "google" {
  alias  = "another" // alias marks this as an alternate provider
  region = "us-east1"
}

data "google_client_config" "this" {
  provider = google
}

data "google_client_config" "that" {
  provider = google.another
}

output "regions" {
  value = [data.google_client_config.this.region, data.google_client_config.that.region]
}

输出:

$ terraform init
$ terraform apply --auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

regions = [
  "europe-west2",
  "us-east1",
]