platforms/gcp/cloud-run
Deploy a stack service to Google Cloud Run. Bash scripts around gcloud, run from a checkout; this is not an Nx project
and not a pnpm package (no package.json), so it has no build, no tests and nothing imports it. The core stays
cloud-free: images are built by the core docker:build Nx target (scripts/build-docker-image.mjs), and these scripts only
log in to Artifact Registry, push, and deploy.
| File | Purpose |
|---|---|
deploy-cloud-run.sh | Build, push and deploy one service; sync its secrets into Secret Manager |
deploy-gcp.sh | One entry point over the deploy targets (today Cloud Run only) |
cleanup-gcp.sh | Audit, and with explicit flags apply, Artifact Registry and Secret Manager cleanup |
artifact-registry-cleanup-policy.json | Policy applied on each deploy: delete untagged images older than seven days |
lib.sh | Logging, required-setting checks, the --dry-run wrappers (sourced by the three scripts) |
Settings
Nothing is defaulted to a project, region or service. Set these in the environment (or a .env; see below) and run from
anywhere.
| Variable | Used by | Meaning |
|---|---|---|
PROJECT_ID | all | Google Cloud project (required) |
REGION | all | Cloud Run and Artifact Registry region (required) |
REPOSITORY | all | Artifact Registry Docker repository; images are <REGION>-docker.pkg.dev/<PROJECT_ID>/<REPOSITORY>/<service> (required) |
SERVICE | deploy | Service name, or the positional argument / --service (required) |
RUNTIME_SERVICE_ACCOUNT | deploy | Runtime identity (default <service>-runtime@<PROJECT_ID>.iam.gserviceaccount.com, created if missing) |
SERVICE_CONFIG | deploy | Path to the service config (default services/<service>/cloud-run.config.sh, then apps/<service>/...) |
ENV_FILE | deploy | Local file with secret sources (default <repo>/.env) |
REPO_ROOT | deploy | Workspace root (default three levels above the script) |
SECRET_NAMES | cleanup | Space-separated secrets to inspect (or repeat --secret); none means secret versions are skipped |
DRY_RUN | all | true is the same as --dry-run |
cleanup-gcp.sh also takes --project, --region, --repository.
Usage
export PROJECT_ID=my-project REGION=us-central1 REPOSITORY=main-registry
platforms/gcp/cloud-run/deploy-cloud-run.sh --dry-run todo-service # print the gcloud/docker/pnpm commands
platforms/gcp/cloud-run/deploy-cloud-run.sh todo-service # build, push, deploy
platforms/gcp/cloud-run/deploy-gcp.sh --all --service todo-service
platforms/gcp/cloud-run/cleanup-gcp.sh # report only
platforms/gcp/cloud-run/cleanup-gcp.sh --apply --delete-untagged-images--dry-run prints every mutating gcloud command and the pnpm nx docker:build call prefixed with [dry-run], and skips
read-only queries (secret existence, tag bindings); it assumes configured secrets already exist. In cleanup-gcp.sh the
audit queries still run for real (the script is an audit) and only the mutating commands are printed.
Prerequisites: gcloud signed in to the project, Docker running, node, pnpm, and python3 for the cleanup script.
After adding a runtime import to a service, run pnpm sync:deploy-deps <service> first: the bundle keeps npm packages
external, and a missing one crashes the container with MODULE_NOT_FOUND.
What a deploy does
- Enables the Run, Artifact Registry and Secret Manager APIs and ensures the runtime service account exists.
- Applies the Artifact Registry cleanup policy to
REPOSITORY(the repository must already exist). - Syncs secrets (skipped with
--skip-secret-sync): adds a version from each local source, creates missing secrets, applies labels and tags, and grants the runtime accountroles/secretmanager.secretAccessoron every referenced secret. - Logs Docker in to Artifact Registry and runs
pnpm nx docker:build <service>withDOCKER_IMAGE_NAME,DOCKER_PLATFORMS=linux/amd64andDOCKER_PUSH=true; the image is taggedlatestand the package version. - Runs
gcloud run deploy. A revision that fails to start never gets traffic, so the old one keeps serving.
Service config
Each service owns cloud-run.config.sh, a bash file sourced by the deploy script. It sets only non-secret values:
| Variable | Meaning |
|---|---|
SERVICE_PORT | Container port (default 3000) |
SERVICE_ALLOW_UNAUTHENTICATED | true to pass --allow-unauthenticated (default false) |
SERVICE_ENV_VARS | Array of NAME=value plain env vars |
SERVICE_SECRET_REFS | Array of TARGET=SECRET:VERSION for --update-secrets; TARGET is an env var name, or a path (/secrets/key.json=SECRET:latest) to mount a file |
SERVICE_ENV_SECRET_VALUES | Array of ENV_NAME|SECRET_NAME: a new version of SECRET_NAME is added from $ENV_NAME in the environment or .env |
SERVICE_FILE_SECRETS | Array of SECRET_NAME|relative/path: a new version is added from that file in the repo (gitignored) |
SERVICE_SECRET_LABELS | Array of SECRET_NAME|key=value,key=value |
SERVICE_SECRET_TAGS | Array of SECRET_NAME|tagValues/123,tagValues/456 |
SERVICE_PORT=3000
SERVICE_ALLOW_UNAUTHENTICATED=true
SERVICE_ENV_VARS=("NODE_ENV=production" "LOG_LEVEL=info")
SERVICE_SECRET_REFS=("DATABASE_URI=DATABASE_URI:latest")
SERVICE_ENV_SECRET_VALUES=("DATABASE_URI|DATABASE_URI")pnpm nx g @gentlemans-stack/nx-plugin:deployable-service <name> --platform=gcp --deploy=cloud-run writes this file for the
service (port 3000, not public, NODE_ENV/LOG_LEVEL, and the Mongo URI as a secret when the service has a database) and adds a
deploy target, so PROJECT_ID=... REGION=... REPOSITORY=... pnpm nx deploy <name> [--dry-run] runs deploy-cloud-run.sh. Without
--deploy=cloud-run the generator writes nothing (the core assumes no cloud host); copy the shape above into the service. Secret values never go in the config; a secret you do not want a deploy to rotate (an encryption key, say) stays out
of SERVICE_ENV_SECRET_VALUES and is pinned by version in SERVICE_SECRET_REFS (KEY=KEY:1), created once by hand:
openssl rand -base64 32 | gcloud secrets create BROKER_SECRET_KEY --project="$PROJECT_ID" --replication-policy=automatic --data-file=-Keep an offline copy of such a key, never destroy a Secret Manager version that data was encrypted with, and give only project
owners secretmanager.versions.destroy; the runtime account gets secretAccessor only, which the deploy script grants.
To check production secrets match your local files without printing values, compare hashes:
bash -c 'set -a; source .env; set +a; for s in DATABASE_URI; do [ "$(gcloud secrets versions access latest --secret=$s | shasum -a 256)" = "$(printf "%s" "${!s}" | shasum -a 256)" ] && echo "$s match" || echo "$s DIFFERENT"; done'Cleanup
cleanup-gcp.sh without flags only reports: untagged images older than seven days, empty gcf-artifacts repositories, and old
enabled versions of the named secrets. Destructive actions need --apply plus the specific flag (--delete-untagged-images,
--delete-empty-repositories, --destroy-old-secret-versions). The newest enabled secret version and tagged images are never
touched. The registry policy itself is asynchronous; --delete-untagged-images --apply deletes eligible images immediately.
Firebase Hosting in front (optional)
Cloud Run domain mappings are unavailable in some regions (they did not work in europe-west3). The workaround is Firebase
Hosting sites that rewrite every request to the Cloud Run service, with the custom domain on the Hosting site. The Hosting config
names only the service, so a Cloud Run redeploy needs no Hosting deploy; run firebase deploy --only hosting only when the
hosting block of firebase.json changes. Keep the Hosting public directory empty so no static file shadows a route. Limits
of the hop: requests time out after 60 seconds (Hosting's limit, not Cloud Run's); headers such as Authorization pass through
but cookies other than __session are stripped; the CDN caches only responses with a public Cache-Control. A server calling
another service server to server can use the run.app URL and skip the hop. Hosting is not scripted here.
Firebase credentials for the backend
For platforms/gcp/auth-firebase/admin, the service account key for the Firebase project lives gitignored at the repository
root (path overridable in the service's own config) and is mounted from Secret Manager as a file via SERVICE_FILE_SECRETS and
a path-style entry in SERVICE_SECRET_REFS. Never commit it. The /jwks provider needs no key.
Porting to .mjs later
The repo prefers plain-Node scripts (see the script-writer skill). A port would: replace lib.sh's run/query with one
runCommand(argv) over execFileSync; replace the cloud-run.config.sh bash arrays with an exported object in a
cloud-run.config.mjs (the one real change for services); replace the python3 JSON filtering in cleanup-gcp.sh with
JSON.parse; and use scripts/lib/help.mjs for --help. The gcloud argument lists carry over unchanged.