Skip to content

GCP — Practical

Terminal window
gcloud run deploy api \
--source . \
--region eu-west1 \
--allow-unauthenticated \
--service-account api@proj.iam.gserviceaccount.com \
--memory 512Mi --cpu 1 \
--min-instances 1 --max-instances 50 \
--concurrency 80 \
--set-env-vars LOG_LEVEL=info \
--set-secrets=DB_PASS=db-password:latest

Caller fetches an ID token signed by Google for the target audience:

import { GoogleAuth } from 'google-auth-library';
const auth = new GoogleAuth();
const targetUrl = 'https://api-xyz-uc.a.run.app';
const client = await auth.getIdTokenClient(targetUrl);
const r = await client.request({ url: targetUrl + '/items' });

Receiver verifies via Google’s certs (libraries handle this when you require auth).

Terminal window
# bind K8s SA → GCP SA
gcloud iam service-accounts add-iam-policy-binding api@proj.iam.gserviceaccount.com \
--role=roles/iam.workloadIdentityUser \
--member="serviceAccount:proj.svc.id.goog[default/api]"
# annotate K8s SA
kubectl annotate sa api \
iam.gke.io/gcp-service-account=api@proj.iam.gserviceaccount.com

Pod uses K8s SA api; calls to Google APIs work as api@...gserviceaccount.com.

Cloud Build trigger (build → push → deploy)

Section titled “Cloud Build trigger (build → push → deploy)”
cloudbuild.yaml
steps:
- name: gcr.io/cloud-builders/docker
args: ['build','-t','europe-west1-docker.pkg.dev/proj/registry/api:$SHORT_SHA','.']
- name: gcr.io/cloud-builders/docker
args: ['push','europe-west1-docker.pkg.dev/proj/registry/api:$SHORT_SHA']
- name: gcr.io/cloud-builders/gcloud
args:
- run
- deploy
- api
- --image=europe-west1-docker.pkg.dev/proj/registry/api:$SHORT_SHA
- --region=europe-west1
options:
machineType: E2_HIGHCPU_8
SELECT
user_id,
COUNT(*) AS events
FROM `proj.dataset.events`
WHERE _PARTITIONDATE BETWEEN '2026-05-01' AND '2026-05-10' -- partition prune
AND event_type = 'click'
GROUP BY user_id
ORDER BY events DESC
LIMIT 100;

Always:

  • WHERE _PARTITIONDATE on partitioned tables.
  • Avoid SELECT *.
  • Cluster tables on common filters.
import { PubSub } from '@google-cloud/pubsub';
const pubsub = new PubSub();
const topic = pubsub.topic('orders');
await topic.publishMessage({ data: Buffer.from(JSON.stringify(order)) });
const sub = pubsub.subscription('orders-worker');
sub.on('message', async (msg) => {
try { await handle(JSON.parse(msg.data.toString())); msg.ack(); }
catch { msg.nack(); }
});
Terminal window
gcloud secrets create db-password --data-file=- <<< "supersecret"
gcloud secrets versions access latest --secret=db-password
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
const c = new SecretManagerServiceClient();
const [v] = await c.accessSecretVersion({ name: 'projects/proj/secrets/db-password/versions/latest' });
const password = v.payload?.data?.toString();
Terminal window
gcloud logging read \
'resource.type="cloud_run_revision" AND resource.labels.service_name="api" AND severity>=ERROR' \
--limit=50 --format=json

In Logs Explorer: resource.type="k8s_container" AND jsonPayload.level="ERROR" AND timestamp>="...".

provider "google" { project = var.project, region = var.region }
resource "google_project_service" "apis" {
for_each = toset(["run.googleapis.com","artifactregistry.googleapis.com","secretmanager.googleapis.com"])
service = each.value
}
resource "google_artifact_registry_repository" "main" {
location = var.region
repository_id = "registry"
format = "DOCKER"
}
resource "google_cloud_run_v2_service" "api" {
name = "api"
location = var.region
template {
service_account = google_service_account.api.email
containers {
image = "europe-west1-docker.pkg.dev/${var.project}/registry/api:${var.tag}"
resources { limits = { memory = "512Mi" } }
}
}
}
resource "google_access_context_manager_service_perimeter" "p" {
parent = "accessPolicies/${var.policy_id}"
name = "accessPolicies/${var.policy_id}/servicePerimeters/data"
title = "data"
status {
restricted_services = ["bigquery.googleapis.com","storage.googleapis.com"]
resources = ["projects/${var.project_number}"]
}
}
Terminal window
gcloud projects describe $PROJECT
gcloud auth application-default login # for SDK auth
gcloud auth print-identity-token --audiences=https://api...run.app
gcloud run services describe api --region eu-west1 --format json
gcloud logging tail 'resource.type="cloud_run_revision"' --format=json
gcloud iam service-accounts list
gcloud beta run services proxy api --port=8080 # tunnel local