How to get default GCP project and region with Terraform?

3.7k views Asked by At

The standard terraform boilerplate for Google Compute Engine (GCE/GCP) is:

provider "google" {}

How can I get my default project and region with that? I need something analogous to aws_region in AWS (like in this question).

In some cases these are specified externally in the environment variables:

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

Less often they are explicitly visible in hcl code:

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

How to proceed when neither is the case?

1

There are 1 answers

1
kubanczyk On

Basic

Use the google_client_config data source:

data "google_client_config" "this" {}

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

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

Mutliple providers

This can be used even with multiple providers:

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]
}

Output:

$ terraform init
$ terraform apply --auto-approve

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

Outputs:

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