GCP Authentication

To deploy infrastructure on Google Cloud Platform (GCP) using Terraform, you must authenticate Terraform to your GCP project. This guide covers real-life scenarios for local development, CI/CD pipelines, and multi-project setups, with best practices for security and automation.


1. Local Development: gcloud CLI & Application Default Credentials

The recommended way to authenticate locally is to use the Google Cloud SDK (gcloud).

gcloud auth application-default login

This command creates an Application Default Credentials (ADC) file at ~/.config/gcloud/application_default_credentials.json.

Provider block example:

provider "google" {
  project = var.gcp_project
  region  = var.gcp_region
}

Terraform will automatically use ADC if no credentials are specified.

Best Practice: Use named configurations for multiple projects:

gcloud config configurations create dev
# Set project, region, etc.
gcloud config set project my-dev-project
gcloud config set compute/region us-central1
gcloud config configurations activate dev

2. Service Account Key File (for CI/CD and Automation)

For automation (GitHub Actions, GitLab CI, Azure Pipelines), use a GCP Service Account with the required IAM roles. Download its JSON key and store it securely (never commit to code).

Set the environment variable:

Provider block example:

GitHub Actions Example:

GitLab CI Example:


3. Workload Identity Federation (OIDC for CI/CD)

For passwordless, keyless authentication in CI/CD, use Workload Identity Federation. This is the most secure and recommended approach for production pipelines.

  • Configure a Workload Identity Pool and Provider in GCP.

  • Grant the pool access to the required GCP resources.

  • Use OIDC tokens from GitHub Actions, GitLab, or Azure DevOps to authenticate.

GitHub Actions Example:


4. NixOS: Declarative GCP Credentials

Add credentials as environment variables in your NixOS configuration:

Or use agenix for encrypted secrets.


Best Practices

  • Use Workload Identity Federation (OIDC) for CI/CD pipelines (no static keys)

  • Store service account keys in secret managers (never in code)

  • Grant least privilege IAM roles to service accounts

  • Rotate and audit service account keys regularly

  • Use named gcloud configurations for multi-project workflows

  • Never use user credentials in automation


References

Tip: For secure, auditable, and cloud-native deployments, prefer OIDC-based authentication for CI/CD and never commit service account keys to your repository.


Last updated