Rails 8 on Google Cloud: From Zero to AI

1. Introduction

Welcome to the Rails 8 on Google Cloud workshop! In this hands-on codelab, you will take a modern Rails 8 application from a simple local SQLite baseline to a production-grade, enterprise-ready reference architecture on Google Cloud.

In this workshop we don't just deploy an app — we execute an opinionated, production-grade cloud modernization (lift-and-shift done right!).

You start from the typical "works on my machine" local setup (ephemeral disk, embedded SQLite, in-process jobs) and progressively evolve it into an enterprise, bulletproof cloud architecture on Google Cloud:

  1. 🐘 From Local SQLite → Cloud SQL (PostgreSQL): No more DB wiped on restarts. We move to managed PostgreSQL connected securely via Cloud SQL Auth Proxy (mTLS, no public IPs).
  2. 🪣 From Ephemeral Local Storage → Private GCS: Serverless disk is temporary. We wire ActiveStorage to private Google Cloud Storage using IAM signed URLs (iam: true) — no public buckets, no leaked keys.
  3. 🚀 From In-Process Jobs → Multi-Container Cloud Run: We bridge the Rails monolith and serverless cloud! Using standard Docker Compose, we run Solid Queue as a dedicated worker container alongside Puma in a Cloud Run multi-container pod — zero microservice sprawl, zero thread starvation, DHH would be proud!

🍌 And because we live in 2026, we supercharge the whole stack with Google Antigravity. This is not an after thought, we have prompts and skills to guide your harness to better execute (and enjoy) this workshop!

🏛️ Target Reference Architecture (Variant 1: Clean Flat Vector Enterprise)

Here is the canonical Google Cloud reference architecture you will build and deploy (Variant 1: Clean Flat Vector Enterprise), showcasing our production multi-container Cloud Run service connected to all managed Google Cloud persistence and AI services:

Variant 1: Clean Flat Vector Enterprise — Rails 8 on Google Cloud Architecture

🎞️ The Architectural Evolution: From Zero to Cloud-Native

Watch our stack progressively modernize from an ephemeral single-machine baseline to a fully managed Google Cloud blueprint across each workshop milestone:

Workshop Architectural Evolution

What you'll learn

Let's get started!

2. Step 0: Prerequisites, Antigravity Setup & Billing Verification

💡 The Scenario: You and your team are building a mission-critical Rails 8 application. Before touching code or launching cloud resources, we must establish our toolchain, connect Google Antigravity, and verify our Google Cloud credentials and billing foundation.

1. Prerequisites Checklist

Before we begin, ensure you have the following tools available in your environment:

  • just (1.21+): (just --version) the task runner — every single command in this workshop is a just recipe (ask your AI harness to install it, or see skills/rails8app-workshop).
  • Git (2.30+): (git --version) for version control, branching, and cloning the repository.
  • Google Cloud SDK (gcloud CLI): Installed and up to date.
  • Terraform CLI (1.5+): For declarative infrastructure provisioning.
  • docker & docker-compose: Installed and running locally. (Fast-Track Tip: Using Docker Compose, VS Code DevContainers (.devcontainer/devcontainer.json), or Google Cloud Shell gets you running in < 2 minutes without compiling Ruby on your host!)
  • Ruby 3.4.5: (ruby -v — pinned by blog/.ruby-version; pre-installed inside our Docker Compose & DevContainer images, or ask your AI harness to install 3.4.5 if running natively on host). Rails 8 is declared in the Gemfile and installed automatically by bundle install.
  • Google Antigravity 2.0: Your autonomous AI pair programming assistant (Download Google Antigravity 2.0). You'll login with your personal Gmail — no API token needed.

2. Configure Environment Variables, Dedicated gcloud Profile & ADC

⚠️ Warning for Google Cloud Shell & Pre-Configured Workshop VMs: NEVER run gcloud init! If you are running inside Google Cloud Shell, a Qwiklabs / CloudVLab VM, or a pre-provisioned Antigravity workshop workstation, your Google Cloud credentials are already active (and you do not need to open a nested Incognito window or Cloud Shell inside the VM). Do NOT run interactive gcloud init — its multi-step interactive prompts ([1] Re-initialize configuration, numbered project/region menus) will hang autonomous AI agents or overwrite pre-configured workshop credentials. Always use the non-interactive gcloud config set commands below!

First, export your core workshop environment variables (GOOGLE_CLOUD_ACCOUNT, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_REGION) before running any gcloud commands:

# 0. Export your workshop identity, target project ID, and Cloud Run region
export GOOGLE_CLOUD_ACCOUNT="your-email@gmail.com"
export GOOGLE_CLOUD_PROJECT="rails8-workshop-$(date +%m%d)-$RANDOM"
export GOOGLE_CLOUD_REGION="europe-west1"

To prevent collisions with existing corporate, personal, or multi-account gcloud setups, create and activate a dedicated named configuration, authenticate, and create (or select) your GCP project:

# 1. Create and activate dedicated workshop configuration (Fixes Issue #38)
gcloud config configurations create rails8-on-gcp-workshop --activate 2>/dev/null || \
  gcloud config configurations activate rails8-on-gcp-workshop

# 2. Authenticate your account and Application Default Credentials (ADC)
gcloud auth login $GOOGLE_CLOUD_ACCOUNT
gcloud auth application-default login

# 3. Create the GCP project (if it does not exist yet) and set active project + Cloud Run region
gcloud projects create $GOOGLE_CLOUD_PROJECT --name="Rails 8 on GCP Workshop" 2>/dev/null || true
gcloud config set project $GOOGLE_CLOUD_PROJECT
gcloud config set run/region $GOOGLE_CLOUD_REGION
gcloud auth application-default set-quota-project $GOOGLE_CLOUD_PROJECT

💡 Why run/region instead of compute/region? Setting compute/region on a brand-new project triggers a prompt to enable compute.googleapis.com (which fails before billing is linked and isn't needed for Cloud Run). Setting run/region configures Cloud Run cleanly without touching Compute Engine!

Active gcloud configuration

3. 🚨 GCP Billing Linkage & Verification

🎟️ Workshop credits? If your proctor offers Google Cloud credits, the claim banner is at the top of this step in the Google-hosted copy of the codelab: codelabs.developers.google.com/codelabs/rails8-on-google-cloud#1 (sign in with a personal Gmail account). The GitHub Pages copy has no banner. Claim the credits first, then come back here.

⚠️ Important — Having an OPEN Billing Account vs. Linking It to Your Project: Running gcloud billing accounts list and seeing OPEN: True only means your billing account exists — you must still link it to $GOOGLE_CLOUD_PROJECT! Also note that temporary workshop credit trials can become SUSPENDED (BILLING_ISSUE) if left overnight, so we recommend completing the cloud steps in a same-day single session.

Link your active billing account to $GOOGLE_CLOUD_PROJECT and verify that billingEnabled: true is returned:

# 1. Find your open Billing Account ID (e.g. 01ABCD-23EFGH-45IJKL)
gcloud billing accounts list

# 2. Link the billing account to your workshop project
export BILLING_ACCOUNT_ID=$(gcloud billing accounts list --filter="open=true" --format="value(ACCOUNT_ID)" --limit=1)
gcloud billing projects link $GOOGLE_CLOUD_PROJECT --billing-account=$BILLING_ACCOUNT_ID

# 3. Confirm billingEnabled: true
gcloud beta billing projects describe $GOOGLE_CLOUD_PROJECT

You can also link or verify your project's billing account directly in the browser at: https://console.cloud.google.com/billing/linkedaccount?project=$GOOGLE_CLOUD_PROJECT (or redeem your workshop credit coupon in the Google Cloud Console Billing Page).

Active GCP Billing Account

4. Clone the Repository & Pair with Antigravity

Clone the repository and enter the directory. Notice that we stay entirely on main:

git clone https://github.com/palladius/rails8-app-on-gcp.git
cd rails8-app-on-gcp

Open this directory in Google Antigravity. Antigravity will automatically inspect the repository, read AGENTS.md, and stand by as your pair programmer.

🧰 Already have a coding harness you like? Keep it. Claude Code, Codex, Gemini CLI and Cursor work too: CLAUDE.md and GEMINI.md are symlinks to AGENTS.md, and the repo's skills are linked under .claude/skills and .agents/skills. Use the same prompt below. No harness yet? Download Antigravity and sign in with your personal Gmail account: no API key and no subscription needed to start.

Once inside, open the prompt box and kick off your pairing session with this prompt:

I am attending the Rails 8 on Google Cloud workshop.
Please inspect:
https://github.com/palladius/rails8-app-on-gcp/blob/main/workshop/landing-page/README.md
and guide me step-by-step through the workshop in [YOUR LANGUAGE]!

Antigravity will ingest the repository directives, guide you step-by-step through the codelab, and speak with you in your favorite language (🇬🇧 English, 🇮🇹 Italian, 🇫🇷 French, 🇧🇷 Portuguese, 🇩🇪 German)!

5. 🪫 If Antigravity Runs Out of Free Credits

⚠️ The Cloud credits you just redeemed do NOT refill Antigravity. They are two separate billing surfaces: Antigravity's quota sits on Google AI plans (Google One), while vouchers and Cloud credits land on a Cloud Billing account. Linking a billing account to your GCP project will not give you a single extra Antigravity prompt.

If the agent stops with a quota message, work down this ladder — the first two are free and instant:

  1. Switch model pool. Quota is tracked per model family, and Antigravity shows two independent pools (Gemini models vs. Claude/GPT models). Claude and GPT-OSS models are available on the free tier, so a drained Gemini pool often leaves the other one untouched. Use the model selector under the prompt box.Antigravity model selector — switch between Gemini, Claude and GPT-OSS pools
  2. Pick a Flash model instead of Pro. Rate limits correlate with how much work the agent does per request, so a lighter model stretches what is left.
  3. Use the Antigravity CLI with your own key. Bring-your-own-key is not supported in the Antigravity IDE — the CLI is the documented alternative. Create a free key in Google AI Studio (needs a project but no billing account), then download and configure the Antigravity CLI. (Note: this key is strictly for the external CLI harness — per Constitution §11, our Rails 8 application code never uses static API keys and authenticates 100% via keyless Vertex AI ADC!)
  4. Wait, or upgrade. Free-tier quota refreshes weekly (the error message states your reset date). Google AI Pro/Ultra is the only documented way to raise the baseline inside the desktop app; those plans refresh every five hours and can spend purchased AI credits on overage.
  5. Any other AI coding harness works too: the repo ships AGENTS.md (also linked as CLAUDE.md and GEMINI.md) and a skills/ directory.

6. Automated Step 0 Validation

Verify that your Step 0 environment is 100% compliant with the evaluation suite:

just workshop-eval 0

✨ The Wow Moment: Antigravity and the workshop evaluation engine verify your CLI versions, Ruby environment, and ADC authentication in under 2 seconds!

3. Step 1: Terraform Infrastructure Kickoff & Pre-Flight Diagnostics

💡 The Strategy: Managed databases like Google Cloud SQL PostgreSQL take approximately 10–12 minutes to provision. Rather than waiting idly later, we launch immutable infrastructure via Terraform right now in the background while we develop locally!

1. Initialize .env & Run Automated Pre-Flight Diagnostics Suite

First, create your .env file from the documented .env.dist template (also symlinked as .env.example for convenience) and populate your GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_REGION, and GOOGLE_CLOUD_ACCOUNT variables:

cp .env.dist .env   # (or: cp .env.example .env)
# Edit .env (or populate it from your exported shell variables) and load it:
set -a && source .env && set +a

📋 What lives inside .env? (Loaded automatically by dotenv-rails & Docker Compose)

  • GOOGLE_CLOUD_ACCOUNT: Your Google email (used for Billing checks, Terraform IAM bindings, and seeded Blog Admin login).
  • GOOGLE_CLOUD_PROJECT: Your active GCP Project ID (used by Terraform, ActiveStorage GCS, and Vertex AI ADC).
  • GOOGLE_CLOUD_REGION: Deployment region for Cloud Run, Cloud SQL, and GCS (default europe-west1).
  • GOOGLE_CLOUD_LOCATION: Vertex AI endpoint location (default global).
  • PORT: Optional local HTTP port override (default 3000 locally, 8080 on Cloud Run).
  • Security Note (Constitution §11): Never add static Gemini API keys to .env — the app authenticates to Vertex AI strictly via keyless Application Default Credentials (ADC)!

Now run the comprehensive pre-flight diagnostics suite before launching cloud infrastructure:

just workshop-test

This script (bin/workshop_diagnostics.rb):

  • Verifies your GOOGLE_CLOUD_ACCOUNT identity configuration.
  • Verifies active billing and project linkage.
  • Validates Application Default Credentials (ADC) for Vertex AI.
  • Automatically ensures blog/config/master.key and blog/config/credentials.yml.enc are cryptographically paired via bin/ensure_workshop_credentials.rb (replacing the author-only WORKSHOP_FILE_MD5_EMI_RICC file before Terraform uploads rails-master-key to Secret Manager).
  • Confirms the ActiveStorage canary seed image (blog/app/img/gcs_dev_image.jpg).

just workshop-test diagnostics output

💡 Tip: If just workshop-test reports that the billing API is disabled on your project, enable it quickly via:

gcloud services enable cloudbilling.googleapis.com

2. ⏱️ Launch Terraform Infrastructure Asynchronously

Run the one-step Terraform recipe, which creates the remote backend state bucket and triggers the infrastructure deployment:

just terraform-apply

Terraform successfully initialized

Manual alternative (or run `iac/bin/terraform-apply.sh` directly)

# Fall back to active gcloud config if environment variables are unset
GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project)}"
GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-europe-west1}"

# Create remote state bucket idempotently
gcloud storage buckets create "gs://${GOOGLE_CLOUD_PROJECT}-tfstate" --location="$GOOGLE_CLOUD_REGION" 2>/dev/null || \
  gcloud storage buckets describe "gs://${GOOGLE_CLOUD_PROJECT}-tfstate" >/dev/null

cd iac
terraform init -backend-config="bucket=${GOOGLE_CLOUD_PROJECT}-tfstate"
terraform apply -auto-approve -var="project_id=${GOOGLE_CLOUD_PROJECT}" -var="region=${GOOGLE_CLOUD_REGION}"
cd ..

What Terraform Provisions:

  • Google Cloud Storage Bucket: Created with private access and IAM Credentials signing (iam: true).
  • Canary Test Image: Uploads gcs_dev_image.jpg to the bucket to enable end-to-end blob verification.
  • Google Cloud SQL PostgreSQL Instance: Initiates background provisioning (~10-12 minutes).

Cloud SQL PostgreSQL instance in Google Cloud Console

💡 Note: You can safely ignore the warning about missing automated backups — we won't need them for this workshop database (although automated daily backups are an essential best practice for any real production database!).

Terraform apply completed successfully with outputs

📝 Take note of your Cloud Run URL: The Terraform apply should succeed and print your infrastructure outputs. Note down your cloud_run_url (or copy it to your clipboard) — you'll need it in later steps when verifying your live service!

3. Automated Step 1 Validation (Optional)

Verify that your Step 1 prerequisites and configurations pass:

just workshop-eval 1

⏱️ Note: This evaluation checks live cloud resources and may take a couple of minutes to finish. It is completely optional — while it runs in your terminal, you can immediately proceed to the next step without waiting!

4. Step 2: The Local Baseline, Mailpit & Admin Onboarding

Our starting point is a clean, modern Rails 8 blog application running on localhost with Docker Compose, Mailpit email interception, and disk-based ActiveStorage.

1. Boot the App Locally via Docker Compose

🐳 Canonical Local Stack (just compose-up) Docker Compose runs the exact pinned Ruby 3.4.5 stack, PostgreSQL 16, Solid Queue worker, Mailpit, and Adminer inside isolated containers — zero host gem permission issues! Our blog/compose.yaml automatically loads your root .env, removes any stale tmp/pids/server.pid, runs db:prepare across all 4 databases (primary, cache, queue, cable), and seeds your admin user (GOOGLE_CLOUD_ACCOUNT with password Ch4ng3m3-1 or APP_ADMIN_PASSWORD).

From the repository root (or inside blog/), launch the full local stack in one command:

just compose-up
# Or from inside blog/:
# cd blog && docker compose up -d

⚙️ Optional: Running Native Host Ruby 3.4.5 via rbenv (Instead of Docker / DevContainers)

💡 Fast-Track Reminder: Because just compose-up (or opening the repo in VS Code DevContainers via .devcontainer/devcontainer.json) already provides a pre-built Ruby 3.4.5 container, you do NOT need to compile Ruby on your host machine to complete this workshop!

If you still want to run Rails CLI commands natively on your host shell (bin/rails test, etc.) outside Docker containers:

  1. First install the required native C/YAML build headers (prevents psych / libyaml compilation errors during rbenv install and bundle install):
    # Debian / Ubuntu / Google Cloud Shell / gLinux:
    sudo apt-get update && sudo apt-get install -y \
      build-essential libssl-dev libreadline-dev zlib1g-dev libyaml-dev libffi-dev
    
  2. Initialize rbenv in your standard bash or zsh shell (or rbenv init - fish | source if you use fish) so Ruby 3.4.5 is active instead of system Ruby:
    cd blog
    eval "$(rbenv init - bash)"   # or: eval "$(rbenv init - zsh)"
    ruby -v                       # must print 3.4.5
    bundle install
    bin/rails db:prepare db:seed
    

2. 🌱 Smart Seed Auto-Discovery & Admin Bootstrap (Issue #21 & #25)

The database seed (db/seeds.rb) features Smart Environment Auto-Discovery:

  • It inspects your active database adapter (SQLite vs Postgres) and storage configuration.
  • It detects Stage 0 (Localhost) and automatically creates (or updates the password of) the initial admin user from GOOGLE_CLOUD_ACCOUNT with APP_ADMIN_PASSWORD (default Ch4ng3m3-1), and seeds the pedagogical post:
    • [LOCAL BASELINE] Welcome to Rails 8 on Localhost!
    • Out-of-the-box local sad image attachment (local_sad_image.png) with watermark informing you that local disk storage is ephemeral.
  • It automatically triggers a password reset email via ActionMailer.

Docker Compose starting Rails, Mailpit, and local stack

The application, local Mailpit SMTP server, and Adminer database viewer are now running together in isolated containers:

  • Rails App: http://localhost:3000
  • Mailpit Web UI: http://localhost:8025
  • Adminer DB UI: http://localhost:8081

🧯 Port 3000 conflict or server.pid error? If you previously started a native dev server (bin/dev), stop it with Ctrl+C. blog/bin/docker-entrypoint automatically cleans up stale tmp/pids/server.pid on container boot, or you can restart cleanly anytime via:

just compose-down
just compose-up

3. The Mailpit Experience & Admin Login

  1. Catch Outgoing Emails with Mailpit: Open http://localhost:8025 in your browser. Look at the local inbox! During db:seed, ActionMailer dispatched an admin onboarding email which Mailpit safely captured locally without touching external email servers or credentials:

Mailpit web UI displaying intercepted password reset email 2. Log into the Blog: Open http://localhost:3000 in your browser.

  • You can click the password reset link directly inside the Mailpit email to set your password.
  • Alternatively, log in using your Google Cloud account email (GOOGLE_CLOUD_ACCOUNT from .env) and the seeded password: Ch4ng3m3-1 (or your custom APP_ADMIN_PASSWORD if set in .env).
  1. Observe the Visual Telemetry Badges:
    • Notice the yellow environment banner and badges in the UI: Notice: Ephemeral Database Active (POSTGRESQL) and [EPHEMERAL DB / STORAGE] 💾 Local.
    • Notice the post watermark: The 🏠 stamp (nanobanana_stamp_local.png in the bottom-right corner of the cover image). This provides immediate visual confirmation that your assets and database are currently bound to ephemeral local storage.
    • Create a post without a cover image and wait a few seconds: the app attaches a bundled placeholder poster (nanobanana_fake_cover.png), not an AI-generated one. This is expected: the Docker Compose containers hold no Google credentials, so the app skips Vertex AI instead of failing (Constitution §6 and §11). The real AI poster arrives in Step 7, on Cloud Run.

Local blog homepage displaying ephemeral telemetry notices and badges

💡 Optional Pro-Tip: Rails Console Workout Curious how Rails interacts with your seeded data from the CLI? Drop into the interactive console:

docker compose exec web ./bin/rails console

Inspect your seeded admin user dynamically using your environment variable:

user = User.find_by(email_address: ENV.fetch("GOOGLE_CLOUD_ACCOUNT"))
# Or simply grab the first user:
user = User.first
puts "Admin email: #{user.email_address} (created via: #{user.created_via})"
exit

4. Automated Step 2 Validation

Verify your local baseline and admin setup:

just workshop-eval 2

just workshop-eval 2 verification output

5. The Catch: Stateless Containers

Cloud Run containers are stateless and ephemeral. If we deploy our SQLite database and local storage/ directory directly to Cloud Run, all posts and uploaded images will be permanently wiped out whenever a container scales to zero or restarts.

In the next step, we will intentionally deploy this ephemeral configuration to Cloud Run to witness the Stateless Shock first-hand!

5. Step 3: Deploy 1 & Deploy 2 — The Stateless Shock (Early WOW)

Instead of waiting 15–20 minutes for cloud databases before seeing anything on the web, modern serverless development begins with an early victory: deploying our single-container Rails application directly to Google Cloud Run with one command (about six minutes the first time, while Cloud Build builds the image).

1. The Time-Machine Rewind

To guarantee that our starting configuration is 100% ephemeral (local SQLite database and local disk file storage), use the Zero-Branch Time-Machine engine:

just workshop-rewind 1

💡 What just happened?workshop-rewind 1 applied the stage-1-stateless configuration overlay to blog/config/ without leaving the main branch. Your app is configured with SQLite on container disk and ActiveStorage on local filesystem.

2. Deploy 1: Deploying Single-Container Puma to Cloud Run

Deploy directly from source code to Cloud Run using the dedicated rails-cloudrun-sa Service Account created by Terraform in Step 1. Modern Rails 8 automatically generates an official, production-ready Dockerfile out of the box (with multi-stage builds, jemalloc, and non-root security). When you deploy from the blog/ folder, Google Cloud Build detects this native Dockerfile directly and provisions a managed serverless service:

# Ensure you are inside the Rails application directory
cd "$(git rev-parse --show-toplevel)/blog"   # the Rails app folder, from wherever you are in the repo

# Ensure default region and custom Cloud Run Service Account are set
export GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-europe-west1}"
export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"

# Deploy 1: single-container service from source (passing GOOGLE_CLOUD_ACCOUNT and APP_ADMIN_PASSWORD)
gcloud run deploy blog \
  --source . \
  --region $GOOGLE_CLOUD_REGION \
  --service-account $RUN_SA \
  --allow-unauthenticated \
  --set-env-vars GOOGLE_CLOUD_ACCOUNT=$GOOGLE_CLOUD_ACCOUNT,APP_ADMIN_PASSWORD=${APP_ADMIN_PASSWORD:-Ch4ng3m3-1},SECRET_KEY_BASE_DUMMY=1

You should see progress output similar to this:

gcloud run deploy building and deploying container

⏳ Expect about six minutes: Cloud Build builds the image, then Cloud Run starts the revision. Every later

--source

deploy rebuilds the image and takes about as long.

🧯 Troubleshooting & Common Caveats

PERMISSION_DENIED: Build failed because the default service account is missing required IAM permissions? Two different causes wear the same error:

  1. gcloud just enabled an API for you. If the deploy printed The following APIs are not enabled ... cloudbuild.googleapis.com and you answered Y, the build may have started before the new permissions finished propagating — gcloud's own prompt warns "this will take a few minutes". Wait a minute and re-run the exact same command; it usually succeeds. Step 1's terraform apply normally enables this API for you, so you should not see the prompt at all.
  2. The Default Compute SA really is missing roles. Modern GCP projects enforce least privilege on it, which breaks source deploys. Fix it with:
    just project-status   # grants storage.admin, logging.logWriter, artifactregistry.writer, cloudbuild.builds.builder
    
    just workshop-test also reports this now, so it is worth re-running if the deploy keeps failing.
  3. Updating Gemfile / google-cloud-* Gems or Speeding Up Docker Builds: If you add or bump gems on macOS/Windows, run bundle lock --add-platform x86_64-linux so Cloud Build's Linux container resolves precompiled native gems cleanly alongside Rails 8 Propshaft and Psych 5 (libyaml-dev). For faster repeated builds with Artifact Registry Docker layer caching (--cache-from), see cloudbuild.yaml and bin/cloudbuild-submit.

During deployment:

  1. Cloud Run builds your Rails container image.
  2. It assigns a public HTTPS endpoint (https://blog-[hash]-[region].a.run.app) secured with a Google-managed TLS certificate.
  3. Traffic begins routing to Puma on port 8080.

3. ✨ The Early WOW Moment

Open the generated Cloud Run URL in your browser!

  1. Your modern Rails 8 application is live on Google Cloud!
  2. Log in with your admin credentials (GOOGLE_CLOUD_ACCOUNT and the default seeded password Ch4ng3m3-1). If you find no login button, click on "New Post" and it will prompt for user and password first:Rails 8 Sign In page with ephemeral telemetry banners
  3. Click "New Post", write an article titled "My First Cloud Run Post", attach a picture, and click Create Post.
  4. Your post is published with full formatting, and your image is rendered.
  5. Notice the visual telemetry:
    • Header badge: [EPHEMERAL DB / STORAGE] 💾 Local
    • Image watermark: The 🏠 stamp (127.0.0.1 ephemeral disk badge in the bottom-right corner).

🐝 Join the Live Workshop Hive Leaderboard! If you are online and your proctor is showing the leaderboard, and you want to join it, add your Cloud Run URL here: 👉 Register your Cloud Run on the Leaderboard

Google Cloud Run Console blog service revision details

4. 💥 Deploy 2: The Stateless Shock & The "Puma Workaround" Trap

Cloud Run is a stateless, serverless platform. When web traffic drops to zero, Cloud Run scales down to zero container instances to save money. When a new HTTP request arrives or a new container revision is deployed, Cloud Run starts a brand new, clean container image.

Stuck Jobs Banner

When you create a post or attach an image in a single-container deployment, Rails enqueues ActiveJob tasks (like image dimension analysis or metadata indexing). But since nobody is running a background worker, you will see the warning banner:

Notice: 8 background jobs currently pending execution

Deploy 2 — The Tempting Fix: Running Solid Queue inside Puma

A clever developer might say: "Wait! Rails 8 lets us run Solid Queue directly inside the Puma web server process by enabling the

SOLID_QUEUE_IN_PUMA=true

environment variable!"

Let's test this workaround on Cloud Run (Deploy 2):

# Deploy 2: Force a revision update to enable Solid Queue inside Puma
gcloud run services update blog \
  --region $GOOGLE_CLOUD_REGION \
  --update-env-vars SOLID_QUEUE_IN_PUMA=true

Now, go back to your browser and refresh the page:

💥 The Stateless Shock:

  1. The Good News: The Solid Queue worker is now active inside Puma! Any new jobs get drained immediately.
  2. The Cold Shower (The Catch!):
    • Because Cloud Run deployed a new revision, the previous container instance was replaced!
    • The article you wrote and the SQLite database file on disk were completely wiped out!
  3. The Architectural Lesson (and 512 MiB OOM Hazard): Running background workers inside Puma forks multiple Ruby processes inside a single 512 MiB container (causing Out-Of-Memory Memory limit of 512 MiB exceeded crashes!) and still does not solve persistence.

Before moving to Step 4, remove SOLID_QUEUE_IN_PUMA and pin --max-instances 1 (so multiple stateless SQLite containers don't split your login sessions):

# Clean up SOLID_QUEUE_IN_PUMA to prevent 512MiB OOM and pin max-instances=1 for Step 4
gcloud run services update blog \
  --region $GOOGLE_CLOUD_REGION \
  --remove-env-vars SOLID_QUEUE_IN_PUMA \
  --max-instances 1

5. Automated Step 3 Validation

Verify your Cloud Run deployment and alert handling:

just workshop-eval 3

✨ The Lesson: Single-container workarounds like SOLID_QUEUE_IN_PUMA are handy for local development, but in modern cloud architecture:

  • Media files require Google Cloud Storage (GCS) (Step 4).
  • Relational data and job queues require managed Google Cloud SQL (Step 5).
  • Heavy background workers belong in a dedicated sidecar container (Step 6).

6. Step 4: Deploy 3 — GCS Persistent Storage & POLA Warning

In this step, we decouple media and file storage from the container disk by switching ActiveStorage to Google Cloud Storage (GCS), using short-lived signed URLs via the IAM Credentials API (iam: true).

Before you touch any config, understand the three things Rails needs to talk to GCS:

① Project ID + Bucket name — Rails must know where to store blobs. The app reads GOOGLE_CLOUD_PROJECT from the environment and derives the bucket name as ${GOOGLE_CLOUD_PROJECT}-activestorage-prod. Your Terraform from Step 1 already created this bucket — no extra work needed.

② A Dedicated Service Account with the right permissions — Our Cloud Run service runs as the custom Service Account provisioned by Terraform: rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com ($RUN_SA). This SA has two essential IAM roles:

  • roles/storage.objectAdmin — to upload and serve blobs
  • roles/iam.serviceAccountTokenCreator on itself — to call the IAM Credentials signBlob API and generate short-lived signed URLs (gsa_email: rails-cloudrun-sa@...)

⚠️ The Tempting Shortcut — public: true The fastest way to get GCS working is to set public: true in storage.yml and grant allUsers:objectViewer on the bucket. Images load instantly, no signing needed. Do not do this. A public bucket leaks all uploaded user media to the open internet, forever. Our blueprint uses iam: true to keep the bucket 100% private — every image URL is a signed, expiring token generated on the fly by the IAM Credentials API.

③ ACTIVE_STORAGE_SERVICE=google — the single env var that flips Rails from local disk to GCS at runtime. No code change, no redeploy of application logic — just one environment variable toggle.

1. The Time-Machine Rewind

Advance the time machine to Stage 2:

just workshop-rewind 2

Inspect blog/config/storage.yml — you'll see the app defines three named GCS environments (dev / test / prod), all using the same secure pattern:

<% gcp_project = ENV.fetch("GOOGLE_CLOUD_PROJECT") { Rails.application.credentials.dig(:gcs, :project) } %>
<% gcs_signer_sa = ENV.fetch("GCS_SIGNER_SA_EMAIL") { "rails-cloudrun-sa@#{gcp_project}.iam.gserviceaccount.com" } %>

google_prod: &google_prod
  service: GCS
  project: <%= gcp_project %>
  bucket: <%= gcp_project %>-activestorage-prod  # ← derived from project ID, no extra env var!
  iam: true        # Sign URLs via IAM Credentials signBlob API (no private key JSON required!)
  gsa_email: <%= gcs_signer_sa %>

# Convenience alias — ACTIVE_STORAGE_SERVICE=google points here
google:
  <<: *google_prod

GCS IAM Signing Architecture

2. Granting IAM Storage & Signing Permissions

Verify (or idempotently re-apply) that your dedicated Cloud Run runtime service account ($RUN_SA) has permissions to sign URLs and upload objects:

export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"
export GCS_BUCKET="${GOOGLE_CLOUD_PROJECT}-activestorage-prod"

# Grant Storage Object Admin to rails-cloudrun-sa
gcloud storage buckets add-iam-policy-binding gs://$GCS_BUCKET \
  --member="serviceAccount:$RUN_SA" \
  --role="roles/storage.objectAdmin"

# Grant Service Account Token Creator (required for IAM signed URLs)
gcloud iam service-accounts add-iam-policy-binding $RUN_SA \
  --member="serviceAccount:$RUN_SA" \
  --role="roles/iam.serviceAccountTokenCreator"

3. Deploy 3: Deploying to Cloud Run with GCS Attached

Re-deploy with GCS enabled. Make sure you are inside the blog/ folder (otherwise Cloud Run attempts to build using Buildpacks instead of the Rails 8 Dockerfile, causing build failures).

Use --update-env-vars (not --set-env-vars) to preserve existing env vars (GOOGLE_CLOUD_ACCOUNT, SECRET_KEY_BASE_DUMMY=1), and explicitly pass GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT so storage.yml resolves ${GOOGLE_CLOUD_PROJECT}-activestorage-prod:

cd "$(git rev-parse --show-toplevel)/blog"   # the Rails app folder, from wherever you are in the repo
export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"

gcloud run deploy blog \
  --source . \
  --region $GOOGLE_CLOUD_REGION \
  --service-account $RUN_SA \
  --update-env-vars GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT,ACTIVE_STORAGE_SERVICE=google

💡 Tip: If the deployment fails, click on the Cloud Build logs link conveniently provided in your terminal output (as shown in the figure below). You can also ask Antigravity for help deciphering and fixing the error!

Cloud Build failure log link in terminal output

4. ✨ The Surviving Image & The Cloud Stamp

  1. Refresh your blog URL.
  2. Create a new blog post titled "Surviving the Cloud" and upload a photo.
  3. Look at the bottom-right corner of the image:
    • The 🏠 stamp is gone!
    • It is replaced by the colorful Cloud GCS Stamp (nanobanana_stamp_cloud.png).
  4. Force another container restart (which should trigger a fourth revision):
    gcloud run services update blog --region $GOOGLE_CLOUD_REGION --update-env-vars RESTART_TRIGGER=$(date +%s)
    
  5. Refresh the page: while the SQLite database reset, the image binary is safe and sound in Google Cloud Storage! Verify via CLI:
    gcloud storage ls -l -r gs://$GCS_BUCKET/
    

Here is a list of uploaded blobs and media objects you might see on the Google Cloud Storage Browser Console in your production bucket (gs://$GCS_BUCKET):

Google Cloud Storage Console bucket details showing persistent image blobs

5. ⚠️ The Catch: Stuck Jobs Warning Banner

When you uploaded the image, ActiveStorage enqueued an analysis job (ActiveStorage::AnalyzeJob) to extract dimensions and metadata.

However, Cloud Run is currently running only one single web container (puma). In Rails 8, Solid Queue stores background jobs in the database, but nobody is executing bundle exec rails solid_queue:start!

Look at the top of your blog page: you will see a bright warning banner rendered by blog/app/views/layouts/_check_stuck_jobs.html.erb.

We are going to solve this properly in Step 6, when we graduate to a production-grade multi-container sidecar architecture with a dedicated worker container running Solid Queue independently from web traffic!

6. Automated Step 4 Validation

Verify your GCS configuration and stuck jobs telemetry:

just workshop-eval 4

7. Step 5: Pre-Flight Checklist: Cloud SQL, Secrets & DB Connectivity

While you mastered stateless containers and Google Cloud Storage in Steps 3 and 4, Terraform has finished cooking your production backend in the background!

Before deploying our full 3-container production sidecar architecture (Deploy 4 in Step 6), this step acts as a fast Pre-Flight Inspection to verify database health, connectivity, and secret access.

0. Bootstrap Environment Variables

Export all required shell variables directly from your Terraform outputs:

# Core project variables (should already be set from Step 0)
export GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-europe-west1}"

# Custom Cloud Run Service Account provisioned by Terraform
export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"

# Cloud SQL instance name (asked to Google Cloud, so it works from any folder)
export SQL_INSTANCE_NAME=$(gcloud sql instances list --format='value(name)' --limit=1)

# GCS bucket names
export GCS_BUCKET="${GOOGLE_CLOUD_PROJECT}-activestorage-prod"

echo "✅ Pre-flight environment variables ready:"
echo "   RUN_SA=$RUN_SA"
echo "   SQL_INSTANCE_NAME=$SQL_INSTANCE_NAME"
echo "   GCS_BUCKET=$GCS_BUCKET"

1. Cloud SQL Health Check

Verify that your managed PostgreSQL instance has finished initial provisioning and is healthy:

echo "Checking instance: $SQL_INSTANCE_NAME"
gcloud sql instances describe $SQL_INSTANCE_NAME --format="value(state)"

The output must be RUNNABLE.

2. (Optional) Testing Database Connectivity from your Laptop

In production, Cloud Run containers connect securely to Cloud SQL via an encrypted sidecar proxy (127.0.0.1:5432) without exposing the database to the public internet (0.0.0.0/0).

ℹ️ Note: This step is completely optional! In Cloud Run, the official Cloud SQL Auth Proxy sidecar container handles mTLS connectivity automatically. You do not need to install anything locally to complete the workshop.

If you have cloud-sql-proxy and psql installed on your machine and want to verify direct connectivity from your laptop:

# Optional: test connectivity via Google-managed mTLS proxy
gcloud sql connect $SQL_INSTANCE_NAME --user=rails_user --database=rails_production

(If prompted for a password, print it with

gcloud secrets versions access latest --secret=rails-db-password

. Otherwise, feel free to skip directly to section 3 below!)

3. Inspecting Terraform-Provisioned Secrets

Never store plain-text database passwords, API keys, or Rails master keys in git or in container environment variables. In modern cloud architecture, we use Google Cloud Secret Manager for zero-trust runtime injection.

ℹ️ Terraform Handled This for You in Step 1:

  1. rails-master-key — for decrypting Rails credentials at runtime.
  2. rails-db-password — a cryptographically secure random password matching the Cloud SQL user.
  3. rails-admin-password — a secure password for your initial administrator user.

Verify that your secrets are present and active in Secret Manager:

gcloud secrets list --filter="name:rails-"

Google Cloud Secret Manager Console listing configured application secrets

🔑 Syncing master.key & credentials.yml.enc (Atomic Key Pairing & Runtime Injection)

In Rails 8, blog/config/master.key (ignored by git) decrypts blog/config/credentials.yml.enc (committed to git) at boot. They form an indivisible cryptographic pair — if Cloud Run boots without a matching RAILS_MASTER_KEY, Rails crashes immediately with ActiveSupport::MessageEncryptor::InvalidMessage.

Run bin/ensure_workshop_credentials.rb --sync-gcp to verify that your local master.key decrypts credentials.yml.enc and sync it to Secret Manager (rails-master-key):

# Works from any folder of the repository (you are probably still inside blog/)
ruby "$(git rev-parse --show-toplevel)/bin/ensure_workshop_credentials.rb" --sync-gcp

🛡️ Dev vs. Production Secret Injection on Cloud Run:

  • Quick Dev / CLI Testing: Pass the key directly via --set-env-vars="RAILS_MASTER_KEY=$(cat config/master.key)".
  • Enterprise Production (Step 6): Mount the secret directly from Google Cloud Secret Manager at container boot using --set-secrets="RAILS_MASTER_KEY=rails-master-key:latest" so plaintext keys never appear in deployment logs or shell history!

4. Verifying Secret Accessor Permissions

In order for Cloud Run containers to mount these secrets as environment variables or volume mounts at boot, the runtime service account ($RUN_SA) needs the roles/secretmanager.secretAccessor role on each secret.

Terraform already granted this secret-level IAM policy binding during Step 1! Verify the IAM policy binding on rails-master-key:

# Verify that Cloud Run runtime SA has Secret Accessor role on rails-master-key
gcloud secrets get-iam-policy rails-master-key \
  --flatten="bindings[].members" \
  --format="table(bindings.role,bindings.members)" \
  --filter="bindings.members:$RUN_SA"

You should see:

ROLE                                 MEMBERS
roles/secretmanager.secretAccessor   serviceAccount:rails-cloudrun-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com

Cloud SQL Auth Proxy Security Comparison

5. Automated Pre-Flight Validation

Run the automated Step 5 test suite to confirm that your database is runnable, secrets are non-empty, and IAM permissions are green:

just workshop-eval 5

8. Step 6: Deploy 4 — Enterprise Multi-Container Sidecars (The Gold Standard)

Now we assemble the ultimate reference architecture: Multi-Container Cloud Run!

1. Restoring the Gold Standard

Restore your repository configuration to the canonical main state:

just workshop-restore-gold

2. Inspecting the 3-Container Production Blueprint

Open blog/compose.prod.yaml and inspect the architecture:

Cloud Run Multi-Container Production Architecture

graph LR
  Client[Internet / HTTPS Client] -->|Port 8080| Web[Web Container: Puma]
  Web -->|Localhost:5432| Proxy[Sidecar: Cloud SQL Auth Proxy]
  Worker[Worker Container: Solid Queue] -->|Localhost:5432| Proxy
  Proxy -->|IAM mTLS Tunnel| CloudSQL[(Google Cloud SQL PostgreSQL)]

The production deployment runs three coordinated containers sharing the same local network:

  1. web: Serves HTTP traffic on port 8080 via Puma.
  2. worker: Dedicated background processing container running bundle exec rails solid_queue:start.
  3. cloudsql-proxy: Official Google Cloud SQL Auth Proxy sidecar (gcr.io/cloud-sql-connectors/cloud-sql-proxy:2) bound to 127.0.0.1:5432.

Look at the environment: blocks: there is a DB_HOST, a DB_USER and a DB_NAME, but no password and no RAILS_MASTER_KEY. Secrets never go into this file; Cloud Run mounts them from Secret Manager in section 4.

3. Deploy 4a: Three Containers from compose.prod.yaml

blog/compose.prod.yaml holds no secret values: no database password, no RAILS_MASTER_KEY. Deploy it as it is:

cd "$(git rev-parse --show-toplevel)/blog"   # the Rails app folder, from wherever you are in the repo

# Plain settings read by compose.prod.yaml (nothing secret here)
export SQL_INSTANCE_NAME="${SQL_INSTANCE_NAME:-$(gcloud sql instances list --format='value(name)' --limit=1)}"
export CLOUDSQL_INSTANCE_CONNECTION_NAME="${GOOGLE_CLOUD_PROJECT}:${GOOGLE_CLOUD_REGION}:${SQL_INSTANCE_NAME}"
export GCS_BUCKET="${GOOGLE_CLOUD_PROJECT}-activestorage-prod"
export ACTIVE_STORAGE_SERVICE="google"
export GOOGLE_CLOUD_ACCOUNT="${GOOGLE_CLOUD_ACCOUNT:-$(gcloud config get-value account)}"

# Deploy the three containers to Cloud Run (about 6 minutes: it builds the image)
gcloud run compose up compose.prod.yaml \
  --region=$GOOGLE_CLOUD_REGION

Google Cloud Run Console Containers tab displaying the 3 sidecar containersGoogle Cloud Run Console: ‘Containers' tab displaying all three sidecar containers (

cloudsql-proxy

,

web

,

worker

)

Open your Cloud Run URL. The three containers are running, but the "Ephemeral Database Active (SQLITE3)" banner is still there: without the database password, config/database.yml stays on SQLite, and Rails signs sessions with a throwaway key (SECRET_KEY_BASE_DUMMY). The service also runs as the Default Compute service account, because compose up cannot set one.

💡 UI Curiosity / Console Glitch: In the Console dropdown, you may notice Cloud Run labels the top entry as Ingress container: cloudsql-proxy. This is a visual glitch in the Google Cloud Console (tracked in #149). web is the only container listening on HTTP port 8080; cloudsql-proxy only serves PostgreSQL traffic on port 5432.

🧯 Cloud Resource Manager API has not been used in project ... or it is disabled? Step 1 enables this API for you. If your infrastructure predates that change, run gcloud services enable cloudresourcemanager.googleapis.com, wait half a minute, and run compose up again.

4. Deploy 4b: Secrets from Secret Manager

One command mounts both secrets on web and worker, removes the throwaway key and switches to the dedicated service account ($RUN_SA):

export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"
export APP_SECRETS="RAILS_MASTER_KEY=rails-master-key:latest,DB_PASSWORD=rails-db-password:latest"

gcloud run services update blog \
  --region=$GOOGLE_CLOUD_REGION \
  --service-account=$RUN_SA \
  --container=web    --remove-env-vars=SECRET_KEY_BASE_DUMMY --set-secrets="$APP_SECRETS" \
  --container=worker --remove-env-vars=SECRET_KEY_BASE_DUMMY --set-secrets="$APP_SECRETS"

The new revision finds DB_PASSWORD, so config/database.yml switches to PostgreSQL through the cloudsql-proxy sidecar (DB_HOST=cloudsql-proxy). On its first boot web prepares the database (db:prepare, the Solid Queue / Cache / Cable schemas, the seed) from bin/docker-entrypoint.

Check that no secret value is stored in the service. Every secret must show up as a reference (secretKeyRef), never as a value:

gcloud run services describe blog --region=$GOOGLE_CLOUD_REGION --format=yaml | grep -B1 -A3 secretKeyRef

5. ✨ The Wow Moment: Zero Warnings & Full Cloud Persistence!

Take a deep breath and marvel at your screen: all warning banners have vanished! 🪄

Production Blog on Cloud Run with Zero Warnings and Cloud Persistent PostThe production Rails 8 blog: pristine UI, zero warning banners, and persistent Cloud SQL state!

The application is now officially Production-Grade & Cloud-Native:

  • Backed by managed Google Cloud SQL (PostgreSQL) via secure mTLS tunneling.
  • Media safely stored in private Google Cloud Storage with IAM blob signing.
  • Zero ephemeral storage warnings and zero stuck jobs alerts.

Open your Cloud Run URL:

  1. Look at the telemetry badges:
    • [CLOUD PERSISTENT 🐘 ☁️] is verified in your database seed!
    • Both Google Cloud Run and GCS badges in the footer shine green!
    • The stuck jobs warning banner is completely gone!
  2. Create blog posts and comments.
  3. Restart or redeploy as many times as you like: your data, posts, comments, and assets survive forever in Cloud SQL and GCS!

6. (Optional) Later Migrations as a Cloud Run Job

web prepares the database when it boots. That is convenient for a workshop, and it is safe here because the entrypoint takes a PostgreSQL advisory lock. For a busy production service, a schema change is better run once, before the new revision takes traffic. A Cloud Run Job does that, with the same image and the same secrets:

# The image of the web container (jobs do not support --source)
export BLOG_IMAGE=$(gcloud run services describe blog --region=$GOOGLE_CLOUD_REGION --format=json \
  | ruby -rjson -e 'puts JSON.parse(STDIN.read).dig("spec","template","spec","containers").find { |c| c["name"] == "web" }["image"]')
export CLOUDSQL_CONNECTION="${GOOGLE_CLOUD_PROJECT}:${GOOGLE_CLOUD_REGION}:${SQL_INSTANCE_NAME}"

# A job has no sidecar: Cloud Run mounts the Cloud SQL Unix socket under /cloudsql instead
gcloud run jobs create rails-migrate \
  --image=$BLOG_IMAGE \
  --command "bin/rails" \
  --args "db:migrate" \
  --set-env-vars="DB_HOST=/cloudsql/${CLOUDSQL_CONNECTION},GOOGLE_CLOUD_PROJECT=${GOOGLE_CLOUD_PROJECT}" \
  --set-secrets="$APP_SECRETS" \
  --set-cloudsql-instances="${CLOUDSQL_CONNECTION}" \
  --service-account=$RUN_SA \
  --region $GOOGLE_CLOUD_REGION

gcloud run jobs execute rails-migrate --region $GOOGLE_CLOUD_REGION --wait

Output of gcloud run jobs executions describe JOBNAMEA possible output of

gcloud run jobs executions describe $JOBNAME

Google Cloud Run Jobs Console showing rails-migrate job SucceededGoogle Cloud Run Jobs Console showing

rails-migrate

execution Succeeded

7. Automated Step 6 Validation

Verify the multi-container configuration:

just workshop-eval 6

9. Step 7: Generative AI Pipelines, Podcastifier & The GCS Treasure Hunt 🏴‍☠️

With Solid Queue running in a dedicated container and Google Cloud Storage active, we can unleash asynchronous Generative AI!

1. The NanoBanana Vintage Cover Generator (Ready-to-Use GenAI Pipeline)

NanoBanana Mascot

Good news: this functionality is already fully implemented in the codebase! You don't need to write any code — your task here is to trigger and observe an asynchronous cloud GenAI pipeline in action.

🧠 How it Works Behind the Scenes

  • Authentication (Zero API Keys — Constitution §11): Static Gemini API keys are strictly banned! On Cloud Run the app authenticates to Vertex AI with keyless Application Default Credentials (ADC): the rails-cloudrun-sa service account, granted roles/aiplatform.user. Rails run directly on your host can use gcloud auth application-default login the same way. The local Docker Compose stack holds no credentials, which is why Step 2 showed the placeholder poster.
  • The Pipeline: When an article is created without a cover image, an after_commit callback enqueues GenerateCoverImageJob into Solid Queue.
  • Model: It prompts Google's multimodal model (Gemini 2.5 Flash Image / Imagen on Vertex AI) to generate an authentic vintage 1960s Italian film poster ("Locandina di un film 1960") complete with a cameo banana and a shiny ruby "8".
  • Dynamic Provenance Watermark: Uses libvips to dynamically stamp a visual badge on the corner (colorful cloud stamp on GCS).
  • Turbo Stream Hot-Swap: When the image is attached, Turbo::StreamsChannel.broadcast_refresh_to(post) updates the reader's browser live without a manual page reload!

⏳ Give it a few minutes. On Cloud Run the cover took 2m43s to appear in our last test run. Reload the post if the cover does not show up by itself.

🔐 Verify Vertex AI IAM Permissions (roles/aiplatform.user): Terraform grants roles/aiplatform.user to rails-cloudrun-sa in Step 1. If you ever see 403 PERMISSION_DENIED on Vertex AI in your worker logs, verify or idempotently bind the role with:

export RUN_SA="rails-cloudrun-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com"
gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \
  --member="serviceAccount:$RUN_SA" \
  --role="roles/aiplatform.user"

NanoBanana AI Asynchronous Architecture Sequence Diagram

📐 View Mermaid Sequence Diagram Source

sequenceDiagram
  autonumber
  actor User as 👤 Reader / Author
  participant Web as 🌐 Web (Puma)
  participant DB as 🐘 Cloud SQL (Solid Queue)
  participant Worker as ⚙️ Worker (Solid Queue)
  participant Vertex as 🧠 Vertex AI (Gemini Flash / Imagen)
  participant GCS as ☁️ Google Cloud Storage

  User->>Web: POST /posts (Title & Body, No Cover)
  Web->>DB: 1. Save Post & Enqueue GenerateCoverImageJob
  Web-->>User: Redirect to Post (turbo_stream subscribed)

  Worker->>DB: 2. Dequeue GenerateCoverImageJob
  Worker->>Vertex: 3. Prompt for 1960s Italian Poster (ADC auth)
  Vertex-->>Worker: 4. Raw Image Buffer
  Worker->>Worker: 5. Stamp Provenance Watermark (libvips)
  Worker->>GCS: 6. Attach Blob via ActiveStorage (IAM signBlob)
  Worker->>Web: 7. Turbo::StreamsChannel.broadcast_refresh_to(post)
  Web-->>User: ⚡ Live UI Hot-Swap: Poster magically appears!

🧪 Try It Live!

You can trigger it in two ways:

  • Option A (Web UI): Click New post, enter a title like "Serverless Architecture with Ruby on Rails 8", write some content, and leave the cover image file input empty. Click Create Post.
  • Option B (CLI Runner): Run from your terminal:
    bin/rails runner 'Post.create!(title: "Serverless Architecture with Ruby on Rails 8", body: "Exploring asynchronous AI pipelines with Solid Queue and NanoBanana!")'
    

Wait ~15–30 seconds: watch the Solid Queue worker logs in Cloud Run. The vintage poster will appear directly on your post, complete with the colorful Cloud GCS provenance stamp (nanobanana_stamp_cloud.png) in the bottom-right corner!

2. The Bilingual Podcastifier Quest (Hands-On Antigravity Coding Exercise)

⚠️ Important Notice: Unlike the Cover Generator above, this feature is NOT yet implemented!

If you open blog/app/jobs/podcastifier_job.rb, you will find an empty scaffold stub:

class PodcastifierJob < ApplicationJob
  queue_as :default

  def perform(post_id)
    # TODO(student): COMPLETE_ME — Pair program with Google Antigravity to implement
    # Italian TTS podcast generation using voice 'it-IT-Wavenet-A' via Cloud TTS / ADC!
  end
end

Your mission in this hands-on exercise is to pair-program with Google Antigravity to complete this feature:

  1. Prompt Antigravity:"Help me implement PodcastifierJob in app/jobs/podcastifier_job.rb. It should fetch the Post, translate or synthesize an Italian audio overview using Google Cloud Text-to-Speech (voice ‘it-IT-Wavenet-A' with language code ‘it-IT' via ADC credentials), and attach the audio file to post.podcast_audio_it using ActiveStorage!"
  2. Add Player to View: In app/views/posts/show.html.erb, add an HTML5 player when @post.podcast_audio_it.attached?.
  3. Trigger Synthesis: When saved, Solid Queue will execute the text-to-speech job asynchronously in the background.

Podcastifier Bilingual UI with Dual Audio Players

🎧 Sample Podcastifier Outputs:

💡 Need Help or Got Stuck? A complete, battle-tested reference solution is available on branch solutions/podcastifier. You can inspect it anytime with git diff solutions/podcastifier.

3. [OPTIONAL] 🏴‍☠️ The GCS Treasure Hunt (Console Blob Recovery)

ℹ️ Prerequisite Check: Local cloud-sql-proxy CLI Required This optional exercise connects your local laptop directly to Google Cloud SQL via an encrypted mTLS tunnel. Check if you have the CLI proxy installed:

which cloud-sql-proxy
  • If installed: Proceed below!
  • If NOT installed and you want to do this quest: Install it with:
    # Linux (x86_64)
    curl -o /tmp/cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.14.0/cloud-sql-proxy.linux.amd64
    chmod +x /tmp/cloud-sql-proxy && sudo mv /tmp/cloud-sql-proxy /usr/local/bin/cloud-sql-proxy
    # macOS (Homebrew)
    brew install cloud-sql-proxy
    
  • Otherwise: Feel free to skip to the Step 7 automated validation!

Remember that photo you uploaded back in Step 4 before the container restart wiped out the ephemeral SQLite database? That image file is still sitting safely in your private GCS bucket as an "orphaned blob"!

Let's use the Rails console to rescue it and attach it to a Cloud SQL post:

# Connect to your production database via Rails console and Cloud SQL Proxy
cloud-sql-proxy --port 5432 ${GOOGLE_CLOUD_PROJECT}:${GOOGLE_CLOUD_REGION}:${SQL_INSTANCE_NAME} &
export DB_PASSWORD=$(gcloud secrets versions access latest --secret=rails-db-password)
DATABASE_URL=postgresql://rails_user:${DB_PASSWORD}@127.0.0.1:5432/rails_production bin/rails c

Inside the Rails console:

# 1. Search for orphaned GCS blobs in ActiveStorage
orphan_blobs = ActiveStorage::Blob.where.missing(:attachments)
puts "🏴‍☠️ Found #{orphan_blobs.count} orphaned GCS blobs!"

# 2. Attach the surviving blob to your latest post
if orphan_blobs.any?
  post = Post.last
  post.cover_image.attach(orphan_blobs.first)
  post.save!
  puts "🎉 Rescued blob #{orphan_blobs.first.filename} attached to '#{post.title}'!"
end
exit

Refresh your blog: the photo uploaded during Step 4's Stateless Shock is resurrected and permanently attached to your Cloud SQL post!

4. Automated Step 7 Validation

Verify GenAI jobs and assets:

just workshop-eval 7

10. Step 8: Choose Your Own Adventure / Advanced Quests 🏆

Now that you have mastered the canonical reference architecture, choose your graduation quest!

🛡️ Quest 1: Zero-Trust Google IAP (Identity-Aware Proxy)

  • Difficulty: Medium (Enterprise Security)
  • The Goal: Lock down your Cloud Run application so only your verified Google / Gmail accounts can access it, eliminating password login entirely!
  • How it Works:
    1. An External HTTPS Application Load Balancer terminates Google OAuth and verifies identity before traffic ever reaches Cloud Run.
    2. Google forwards verified identity headers (X-Goog-Authenticated-User-Email).
    3. Rails automatically logs in the verified Google identity via blog/app/controllers/concerns/iap_authenticatable.rb:
      module IapAuthenticatable
        extend ActiveSupport::Concern
        included { before_action :authenticate_via_iap }
      
        private
        def authenticate_via_iap
          return unless (raw = request.headers["X-Goog-Authenticated-User-Email"]).present?
          email = raw.sub(/^accounts\.google\.com:/, "")
          user = User.find_or_create_by!(email_address: email) { |u| u.password = SecureRandom.hex(16) }
          start_new_session_for(user) unless authenticated?
        end
      end
      
    4. Enable the Terraform module in iac/iap.tf with enable_iap = true and specify your allowed Google accounts:
      iap_allowed_users = [var.google_cloud_account]
      

⚠️ Local Simulation (IAP_MOCK_EMAIL) vs. Real Production IAP: For local development and automated tests, IapAuthenticatable supports ENV["IAP_MOCK_EMAIL"] (e.g. simulated-iap-account@example.com). When active, the UI displays an explicit warning banner: ⚠️ This is a fake IAP login based on ENV[IAP_MOCK_EMAIL] — do NOT use in prod!!! Never set IAP_MOCK_EMAIL in compose.prod.yaml or production Cloud Run!

Login recognized by IAP banner

📊 Quest 2: Production SRE Telemetry & Cloud Logging

  • Difficulty: Medium (Observability)
  • The Goal: Stream structured JSON application logs with trace correlation IDs directly to Google Cloud Logging and catch production exceptions in real-time with Cloud Error Reporting.
  • How it Works:
    • Configure blog/config/environments/production.rb to emit structured JSON logs with GCP trace labels.
    • Trigger an intentional test exception and watch Google Cloud Error Reporting group and notify you instantly.

🧠 Quest 3: pgvector Semantic Search & Gemini RAG

  • Difficulty: Hard (GenAI Capstone)
  • The Goal: Search articles conceptually using vector embeddings stored in PostgreSQL on Cloud SQL.
  • How it Works:
    • Enable the vector extension on your Cloud SQL PostgreSQL instance:
      CREATE EXTENSION IF NOT EXISTS vector;
      
    • Add the neighbor gem to blog/Gemfile and generate text embeddings with Gemini (text-embedding-004) on Post#after_save.
    • Perform cosine distance queries (<=>) to power a semantic search bar with Turbo Streams!

⚡ Quest 4: SEO & Performance Audit Assistant

  • Difficulty: Easy / Fun (Developer Experience)
  • The Goal: Audit Core Web Vitals, Largest Contentful Paint (LCP), and Flesch-Kincaid / Fog readability indices using Antigravity and Speedgrapher tools.

🤔 Curiosity Box: Getting a Live Rails Console on Cloud Run

💡 The Question: On traditional VMs or Heroku-style PaaS platforms, developers commonly SSH into a running instance or use heroku run rails console to inspect or fix production data live. What is the Cloud Run-native equivalent, and how do you harden it?

Why gcloud run exec doesn't exist for Cloud Run Services

Cloud Run is a serverless platform: your container may be running as zero, one, or hundreds of identical instances, with no stable identity or addressable shell. This is fundamentally different from Kubernetes (kubectl exec), where a specific pod has a named socket you can attach to.

# ❌ This does NOT exist for Cloud Run Services:
gcloud run services exec blog --region europe-west1 -- rails console

# ✅ This exists for Cloud Run JOBS (non-interactive, one-shot tasks):
gcloud run jobs execute my-job --region europe-west1 --wait

The Four GCP-Native Patterns

Pattern

Command

Interactive?

Security

1. Local proxy + remote DB

DATABASE_URL=... rails console

✅ Full

🔒 Cloud SQL Auth Proxy mTLS

2. Cloud Run Job (one-shot)

gcloud run jobs execute --wait

❌ Script only

🔒 IAM role required

3. Web Console gem + IAP

Browser → /rails/console

✅ Full

🛡️ IAP Zero-Trust

4. Cloud Shell + Proxy

Cloud Shell → bin/rails c

✅ Full

🔒 Google identity

Pattern 1 (Recommended for data inspection): Run a local Rails console that talks directly to your Cloud SQL PostgreSQL via the Cloud SQL Auth Proxy:

# In one terminal: start the auth proxy
cloud-sql-proxy rails8-fl-20260907b-xm8ko4:europe-west1:your-instance

# In another terminal: open a read-write or sandbox console
export DB_PASSWORD=$(gcloud secrets versions access latest --secret=rails-db-password)
DATABASE_URL=postgresql://rails_user:${DB_PASSWORD}@127.0.0.1:5432/rails_production \
  bin/rails console --sandbox

You get full IRB interactivity with zero network exposure — the Cloud SQL Proxy uses mTLS over a Unix domain socket or loopback.

Pattern 3 (Web Console + IAP Zero-Trust, the hardened browser path):

The web-console gem provides a browser-based IRB session. Without protection it is a critical security vulnerability — never expose it publicly. But combined with Google IAP (Quest 1), the Attack surface collapses: only verified Google identities on your allowlist can reach the /rails/console endpoint.

# Gemfile — only load in development/staging, never production without IAP!
gem "web-console", group: :development

# config/environments/production.rb — if IAP is enabled:
config.web_console.allowed_ips = ["0.0.0.0/0"]  # IAP terminates auth before us

⚠️ Pattern 3 requires Quest 1 (IAP) to be enabled first. Without it, /rails/console on a public URL is equivalent to leaving your server room unlocked. With IAP, it becomes a powerful operator tool hardened by Google-grade Zero-Trust.

Ask Antigravity: "Show me how to run

rails console --sandbox

against my Cloud SQL production database safely using the Cloud SQL Auth Proxy."

🏆 Graduating on The Hive: Proctor-Validated Proof-of-Work

Once you have completed your chosen quest, claim your Step 8 Graduation Trophy 🏆 on The Hive Leaderboard:

  1. Submit Your Quest on GitHub:
    • Open a new Issue on the official repository: github.com/palladius/rails8-app-on-gcp/issues/new
    • Title format: 🎓 [Step 8 Completed] :
    • In the body, include a brief description of what you accomplished and a link to your live Cloud Run deployment.
  2. Connect Your Cloud Run App to Your Issue:
    • Note your Issue number (e.g. 88 or the full URL https://github.com/palladius/rails8-app-on-gcp/issues/88).
    • Inject the STEP_8_GHI environment variable into your Cloud Run service:
      gcloud run services update blog \
        --region europe-west1 \
        --update-env-vars STEP_8_GHI=<YOUR_ISSUE_NUMBER>
      
    • Verify that your /status.json endpoint now reports your quest:
      curl -s https://<YOUR_APP>.run.app/status.json | jq .quest
      
      You should see:
      {
        "step_8_completed": true,
        "ghi_issue": 88,
        "ghi_url": "https://github.com/palladius/rails8-app-on-gcp/issues/88"
      }
      
  3. Get Your Proctor Review & Unlock the Golden Trophy:
    • Check The Hive Leaderboard: your row will now display an amber badge: ⏳ GHI #XX review pending.
    • Ask workshop proctors (@palladius, @emilianodellacasa, or @ricc) to inspect your deployment.
    • As soon as a proctor comments LGTM on your issue, The Hive will automatically elevate your progress to 8/8 🏆 with a golden/purple glowing badge and a permanent trophy linking directly to your capstone issue!

11. Conclusion & Clean Up

Congratulations! 🎉

You have built and deployed a production-grade, enterprise-ready Rails 8 application on Google Cloud Platform:

  • Zero-Branch Progression: Mastered modern workflows with Time-Machine overlays on main.
  • Cloud Storage: Scalable, private object storage with IAM blob signing (iam: true).
  • Cloud SQL: Managed PostgreSQL secured with Cloud SQL Auth Proxy mTLS tunnels.
  • Secret Manager: Zero plain-text credentials or .env file leaks.
  • Cloud Run Multi-Container: Isolated Puma web, Solid Queue worker, and proxy sidecars.
  • Generative AI: Asynchronous vintage poster generation and TTS podcast synthesis with Vertex AI.
  • Quests: Zero-Trust IAP, SRE Observability, and pgvector embeddings!

🧹 Resource Clean Up

To avoid ongoing charges after completing the workshop, make sure to clean up your Google Cloud resources! Choose the approach that best fits your environment:

Use this option if you are using an existing or shared Google Cloud project where other resources or data live. It surgically destroys only the resources provisioned during this workshop (Cloud Run services/jobs, Cloud SQL instance, Artifact Registry images, Secret Manager secrets, and GCS buckets), leaving the rest of your project untouched.

# 1. Delete the Cloud Run service and migration job created via gcloud CLI
gcloud run services delete blog --region=$GOOGLE_CLOUD_REGION --quiet 2>/dev/null || true
gcloud run jobs delete rails-migrate --region=$GOOGLE_CLOUD_REGION --quiet 2>/dev/null || true

# 2. Destroy all Terraform-provisioned infrastructure (Cloud SQL, GCS buckets, Secrets, Artifact Registry)
cd iac
terraform destroy -auto-approve -var="project_id=${GOOGLE_CLOUD_PROJECT}" -var="region=${GOOGLE_CLOUD_REGION}"
cd ..

Option 2: Total Project Deletion (Leave Zero Trace 🌪️)

Use this option if you created a dedicated workshop project (e.g., using workshop credits or a sandbox) and want to guarantee that zero trace and $0 ongoing billing remain—instantly terminating Cloud SQL, Cloud Run, Artifact Registry, GCS buckets, and billing links:

gcloud projects delete $GOOGLE_CLOUD_PROJECT --quiet

Codelab Version: v2.5.2 (2026-11-18) — Synchronized across GitHub (

workshop/CODELAB.md

) & Google DevSite (

rails8-on-google-cloud

). See workshop/CODELAB_CHANGELOG.md.