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 resourcesauthentification.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:
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_specis generated fromauthentification.yamlusingtemplatefile()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 APIgateway_id: ID of the gatewayregion: GCP regionproject_id: GCP project IDservice_name: Cloud Run service namecloud_run_service_url: Fallback URL ifdata.google_cloud_run_serviceis 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:
- Terraform Init
- Terraform Import (optional)
- Terraform Plan
- Terraform Apply
Notes
- The OpenAPI spec must include a
hostmatching the gateway hostname:
HOST = "${gateway_id}-${region}.gateway.dev" x-google-backendis used to point to the Cloud Run service URL dynamically.