Google Cloud capstone: deploy Cloud Run and Pub/Sub with Terraform
Deploy an authenticated producer and consumer on Cloud Run with Pub/Sub using Terraform, and add Cloud Storage or BigQuery persistence.
By Invicly Tech, , in Google Cloud Engineering and Services. About 9 minutes to read.
In short
You build the design. First you run the producer and consumer locally against the Pub/Sub emulator. Then you describe both Cloud Run services, the topic, a push subscription and the storage in Terraform, and deploy them.
Think of it like this: The local run is a rehearsal on a small stage. Terraform is the written script that lets the real theatre be set up the same way every time.
Explained simply
Now you build it. You start on your own computer, because it is free and fast. The Pub/Sub emulator is a program that pretends to be Pub/Sub. You send a test order, and your consumer code receives it.
Then you move to the real cloud. Instead of clicking in a web page, you write the setup in Terraform files. Terraform reads them and creates the services, the topic and the storage. If you run it again, it only changes what is different.
Security matters here. The consumer is not open to the world. Only the Pub/Sub push subscription may call it, and it proves who it is with a signed token. Each service account gets one small role.
At the end you send one order and look for it in Cloud Storage or BigQuery. If it is there, the whole chain works.
Press Play on a diagram to walk through it one step at a time.
- 1Emulator
Start the Pub/Sub emulator and set PUBSUB_EMULATOR_HOST.
- 2Local test
Publish a sample order and watch the consumer handle it.
- 3Container image
Build and push both images to Artifact Registry.
- 4terraform plan
Read what will be created before you apply.
- 5terraform apply
Create services, topic, subscription and storage.
- 6Smoke test
Send one authenticated order and find it in storage.
- Runs on your machine, no billing
- No real IAM checks
- No OIDC token on push calls
- Good for message logic and duplicates
- Full IAM and audit logs
- Push subscription signs calls with an OIDC token
- Real retry, dead-letter and retention
- Small cost for usage
- 1Sign OIDC token as push_saPub/Sub to Pub/Sub: Sign OIDC token as push_sa
- Pub/Sub to Consumer service: POST envelope with Authorization header2POST envelope with Authorization header
- Consumer service to IAM check: Is push_sa a run.invoker?3Is push_sa a run.invoker?
- IAM check to Consumer service: Yes, allow4Yes, allow
- Consumer service to Pub/Sub: 200 after data is stored5200 after data is stored
In depth
Run the flow locally first
Prerequisites: the gcloud CLI with the pubsub emulator component, and a container or language runtime for your code. Start the emulator with gcloud beta emulators pubsub start --project=local-dev, then in each terminal run the printed env-vars command so PUBSUB_EMULATOR_HOST points to localhost:8085. Client libraries notice that variable and talk to the emulator, so no credentials are needed. Create a topic and a subscription from a script, publish a sample order and print what the consumer receives. Evidence: your consumer logs the order ID once. Cleanup: stop the emulator with Ctrl+C. Its data lives in memory and disappears.
- No IAM, no OIDC tokens, no quotas in the emulator
- A local push test needs a small HTTP server on localhost
- Do local unit tests for the duplicate check here
Terraform for services, topic and subscription
Prerequisites: a project with billing, and these APIs enabled: Cloud Run, Pub/Sub, Artifact Registry, and Cloud Storage or BigQuery. You also need Terraform and an authenticated gcloud. Define two google_cloud_run_v2_service resources, one google_pubsub_topic, a dead-letter topic, and a google_pubsub_subscription with a push_config. Create separate google_service_account resources and grant each one role, with resources such as google_pubsub_topic_iam_member and google_cloud_run_v2_service_iam_member. Run terraform init, terraform plan, and terraform apply. Evidence: the plan lists the resources you expect and apply ends with outputs such as the producer URL. Rollback: terraform destroy removes what the state tracks.
- Identities
- producer_sa
- consumer_sa
- push_sa
- Messaging
- orders topic
- orders_dlq topic
- orders_push subscription
- Compute
- producer service
- consumer service
- Access
- publisher on topic
- run.invoker for push_sa
- objectCreator on bucket
- Data
- bucket or BigQuery table
Authentication on the push path
When a push subscription has an oidc_token block, Pub/Sub signs each call with an identity token for the service account you name. Cloud Run checks that token against IAM, so the push service account needs roles/run.invoker on the consumer. Keep the consumer private by not granting allUsers. Pub/Sub wraps the event in an envelope: a JSON body with a message that holds base64 data, attributes and a messageId. Your handler decodes the data, checks the order ID and returns a 2xx status to acknowledge. Any other status, or a timeout, makes Pub/Sub retry. Real behaviour such as these tokens cannot be seen in the emulator.
- Return 2xx only after the data is stored
- Use the order ID, not messageId, as the dedupe key
- Set the subscription ack deadline longer than your slowest handler
Persisting events
Two simple choices. Cloud Storage: write one object per order named by order ID, such as orders/2026/12/o-1001.json, and a repeat write replaces the same object. BigQuery: insert a row into an events table with columns order_id, received_at and payload. For BigQuery, grant the consumer account roles/bigquery.dataEditor on the dataset and use the order ID as the key when you merge or deduplicate. Pub/Sub can also write directly into BigQuery with a BigQuery subscription, which is worth knowing as an alternative if you do not need custom code.
Learn it in 5 short steps
About 1h 50m each. Track them with a timer in your plan.
- 1Run the flow locally with the Pub/Sub emulator~1h 50m
- 2Write the Terraform for both services~1h 50m
- 3Grant each service account one role~1h 50m
- 4Wire a push subscription to the consumer~1h 50m
- 5Persist events to Cloud Storage or BigQuery~1h 50m
Key points
- The emulator proves your message logic. It does not prove IAM, push authentication or quotas, so test those in the cloud.
- The consumer service allows only the push subscription's service account to invoke it (roles/run.invoker). Do not make it public.
- Each service account gets one role on one resource, for example roles/pubsub.publisher on the topic only.
- A push subscription needs an OIDC token setting and the consumer's URL as the push endpoint.
- Writing each event with its ID as the key (object name or BigQuery insert ID) makes duplicate writes harmless.
Key terms
Tap a card to flip it. 0/5 known
Examples
resource "google_pubsub_subscription" "orders_push" {
name = "order-events-push"
topic = google_pubsub_topic.orders.id
push_config {
push_endpoint = google_cloud_run_v2_service.consumer.uri
oidc_token {
service_account_email = google_service_account.push_sa.email
}
}
dead_letter_policy {
dead_letter_topic = google_pubsub_topic.orders_dlq.id
max_delivery_attempts = 5
}
}Push subscription with authentication and a dead-letter topic (trimmed).
Local publish to the emulator
With the emulator running and PUBSUB_EMULATOR_HOST set, publish a sample order with a short script. The consumer should log the order ID once. Publishing the same ID twice tests your duplicate check before you spend any money.
import json
from google.cloud import pubsub_v1
pub = pubsub_v1.PublisherClient()
topic = pub.topic_path("local-dev", "order-events")
pub.create_topic(request={"name": topic})
order = {"order_id": "o-1001", "total": 42.5}
future = pub.publish(topic, json.dumps(order).encode(), order_id="o-1001")
print("message id", future.result())Deploy and smoke test
After terraform apply, call the producer with your own identity token. Because the service is private, anonymous calls fail with 403, which is the right result. Then check the bucket for the object. If the object is missing, read the consumer logs first.
terraform apply
URL=$(terraform output -raw producer_url)
curl -X POST "$URL/orders" \
-H "Authorization: Bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json" \
-d '{"order_id":"o-1001","total":42.5}'
gcloud storage ls gs://orders-dev-events/orders/Quick reference
- gcloud beta emulators pubsub start runs the local emulator.
- PUBSUB_EMULATOR_HOST makes client libraries use the emulator.
- The emulator has no IAM or OIDC; test those in a real project.
- terraform init, plan, apply, destroy is the whole loop.
- Push subscription needs oidc_token and run.invoker for that account.
- Return 2xx to acknowledge; any other status triggers a retry.
- Key stored data by order ID so repeats overwrite.
Common mistakes
- Testing only with the emulator and discovering an authentication failure after the first real deploy.
- Granting roles/editor to a service account to make an error disappear.
- Leaving the consumer open to all callers so the push works without setting up the token.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Start the emulator and confirm the environment variable points to it.
- Exercise 2medium
Write the Terraform that gives push_sa permission to call the consumer.
- Exercise 3hard
Design the duplicate check for a Cloud Storage consumer and say what could still go wrong.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need Docker for the local route?
- You need some way to run your service, either a container runtime or a language runtime. Cloud Run itself needs a container image, so you will build one before deploying.
- Is the capstone free?
- Not entirely. Cloud Run, Pub/Sub and small buckets are inexpensive at this volume and some have free tiers, but a billing account is required. Check current pricing and set a budget alert.
- Should Terraform state be kept locally?
- For a solo exercise a local file is acceptable. For a team, use a remote backend such as a Cloud Storage bucket with versioning.