Skip to content

API Gateway Deployment with Terraform in GCP

This section explains how the API Gateway is provisioned and configured using Terraform as part of the CI/CD process.


Files Involved

  • main.tf — contains the Terraform code to manage API Gateway resources
  • authentification.yaml — OpenAPI spec used to define the API structure and backend routing

Terraform Resources

The following resources are defined in main.tf:

1. google_api_gateway_api

Creates a new API Gateway API resource:

resource "google_api_gateway_api" "api" {
  api_id  = var.api_id
  project = var.project_id
}

2. google_api_gateway_api_config

Defines the API configuration, including the OpenAPI specification:

resource "google_api_gateway_api_config" "api_config" {
  api           = google_api_gateway_api.api.api_id
  api_config_id = "${var.api_id}-config"
  project       = var.project_id

  openapi_documents {
    document {
      path     = "spec.yaml"
      contents = base64encode(local.openapi_spec)
    }
  }
}
  • local.openapi_spec is generated from authentification.yaml using templatefile() to inject dynamic values like:
  • Cloud Run URL (from data.google_cloud_run_service)
  • API Gateway host
  • Project ID

3. google_api_gateway_gateway

Deploys the actual gateway instance in a GCP region:

resource "google_api_gateway_gateway" "gateway" {
  gateway_id = var.gateway_id
  api_config = google_api_gateway_api_config.api_config.id
  project    = var.project_id
  region     = var.region
}

This is the public entry point for the deployed API.


📥 Input Variables

Relevant Terraform variables:

  • api_id: ID of the API
  • gateway_id: ID of the gateway
  • region: GCP region
  • project_id: GCP project ID
  • service_name: Cloud Run service name
  • cloud_run_service_url: Fallback URL if data.google_cloud_run_service is not used

Outputs

Terraform exports the following outputs:

output "gateway_url" {
  value = "https://${google_api_gateway_gateway.gateway.default_hostname}"
}

output "api_config_id" {
  value = google_api_gateway_api_config.api_config.api_config_id
}

output "gateway_id" {
  value = google_api_gateway_gateway.gateway.gateway_id
}

These outputs are displayed at the end of the CI/CD pipeline.


CI/CD Integration

In cloudbuild.yaml, the API Gateway steps are:

  1. Terraform Init
  2. Terraform Import (optional)
  3. Terraform Plan
  4. Terraform Apply

Notes

  • The OpenAPI spec must include a host matching the gateway hostname:
    HOST = "${gateway_id}-${region}.gateway.dev"
  • x-google-backend is used to point to the Cloud Run service URL dynamically.