Cloud / IaC · Enterprise

Terraform Modules for Cloud Composer, BigQuery Datasets and Pub/Sub to BigQuery Sinks

Reusable Terraform modules that provision Cloud Composer (Airflow) environments, BigQuery datasets, log-based metrics and Pub/Sub subscriptions that write straight into BigQuery.

  • Terraform
  • Cloud Composer
  • Apache Airflow
  • BigQuery
  • Pub/Sub
  • Cloud Logging
  • IAM
  • Dataform

// Why this matters

Setting up Pub/Sub to BigQuery with Terraform is one of the highest-leverage data-platform patterns on Google Cloud: events arrive on a topic and appear as rows in a table, with almost nothing to operate. Add Cloud Composer for orchestration and you have a complete landing, transform and serve path.

The trouble is repetition. Every team needs a dataset, a topic, a subscription with the right permissions, dead-lettering and an Airflow environment, and every hand-built version differs in some small, painful way: missing partitioning, a subscription that silently cannot write, an environment with a public endpoint.

// The problem

The failure modes are quiet. A BigQuery subscription whose service agent lacks permission does not crash anything; messages just retry and pile up. A table without partitioning becomes expensive to query. A Composer environment created with default networking is reachable more widely than intended, and one running as the default compute account has far more access than any DAG needs.

On the operations side, a failed DAG or a burst of dead-lettered messages should alert the owning team, but logging metrics and alert policies are often skipped because they are tedious to wire.

// The solution

Everything is a module. The dataset module creates the dataset with a location, default table expiration if appropriate, labels and explicit IAM bindings (data owners, editors, viewers as groups). The pipeline module creates a topic with an optional schema, a dead-letter topic, and a BigQuery subscription that writes to a partitioned destination table using the topic schema.

The subscription needs the Pub/Sub service agent to hold the BigQuery data editor role on the dataset and the metadata viewer role, and the dead-letter topic needs the agent to publish and the subscription to subscribe. The module grants these, because forgetting is the number one failure.

The Composer module creates a private-IP environment running as a dedicated service account with only the roles DAGs need (BigQuery job user, data editor on the target datasets, read on the DAG bucket). The image version is pinned and upgrades are deliberate. DAG code is synced into the environment's bucket by a pipeline; see GKE Platform with Concourse CI, Vault and Pub/Sub for another event-driven design on the same cloud.

Health metrics: a log-based metric counts failed task logs and another counts dead-letter publishes, with alert policies attached. I rejected Dataflow for plain landing because a BigQuery subscription removes the whole job for simple cases; Dataflow remains the right tool when you need windowing, joins or enrichment before the write.

How it flows flow1. Dataset → 2. Topic → 3. Gate: write permission → 4. BigQuery subscription → 5. Composer → 6. DAGs → 7. Transform → 8. Metrics → 9. Alert01Dataset02Topic03 · GATEGate: write permission04BigQuery subscription05Composer06DAGs07Transform08Metrics09Alert
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. DatasetBigQuery dataset, tables and access from a module
  2. TopicPub/Sub topic with schema and dead-letter topic
  3. Gate: write permission gatesubscription service agent needs BigQuery editor on the dataset
  4. BigQuery subscriptionmessages land in a table automatically
  5. Composerprivate environment with its own service account
  6. DAGssynced from a bucket or Git into the environment
  7. TransformAirflow runs SQL transforms into curated tables
  8. Metricslog-based metrics count failures and lag
  9. Alertfailures routed to the owning team
Event path to curated tables flow1. Producers → 2. Topic → 3. Subscription → 4. Raw table → 5. Composer DAG → 6. Curated tables → 7. Dead letter01Producers02Topic03 · GATESubscription04Raw table05Composer DAG06Curated tables07Dead letter
Event path to curated tables. Landing is managed by Pub/Sub; transformation is orchestrated by Airflow.
  1. Producersservices publish JSON events
  2. Topicschema-validated Pub/Sub topic
  3. Subscription gateBigQuery subscription writes to a raw table
  4. Raw tablepartitioned by ingestion time
  5. Composer DAGscheduled SQL transforms
  6. Curated tablesmodelled datasets for analysts
  7. Dead letterfailed messages kept for replay
Identitypipeline service accountComposer service accountgroup bindingsStorageBigQuery datasetraw tablecurated tablesMessagingtopic and schemadead-letter topicBigQuery subscriptionOrchestrationComposer environmentDAG bucketprivate networkingHealthlog metricsalert policiesnotification channel
Module layers. Each layer is a module that teams call with a few inputs.

// Before you start

  • Terraform 1.6 or newer with the Google provider
  • A project with the BigQuery, Pub/Sub, Composer and Logging APIs enabled
  • A VPC and subnet with a secondary range plan if you want private Composer
  • Groups for dataset owners, editors and viewers (from your identity module)
  • Permission to grant IAM roles to service accounts
  • A bucket and pipeline process for DAG deployment

// Step-by-step implementation

  1. 01 Step 1. Create the dataset module with explicit access

    Grant access to groups, not individuals, and use authoritative-for-role bindings only where you want drift corrected. Label datasets for cost allocation.

  2. 02 Step 2. Create the raw landing table with partitioning

    A partitioned table keeps query costs predictable. Match the schema to the topic schema when using the topic-schema write option, or use a single data column for raw JSON and parse downstream.

  3. 03 Step 3. Grant the Pub/Sub service agent write access

    This is the step everyone forgets. The Pub/Sub service agent for the project writes on behalf of the subscription, so it needs data editor on the dataset and metadata viewer on the project. Without it the subscription is created fine and then never delivers.

  4. 04 Step 4. Pub/Sub to BigQuery with a dead-letter topic

    Create the topic, the dead-letter topic and the subscription with a retry policy. Writing metadata keeps the message id and publish time. The dead-letter topic receives messages that fail delivery after the configured attempts, so poison messages stop looping.

  5. 05 Step 5. Create the Composer environment with a dedicated identity

    Give Composer its own service account with narrowly scoped roles, run it with private IP and pin the image version. The Composer worker role is required on the service account.

  6. 06 Step 6. Write a DAG that builds a curated table

    Keep transformations as SQL run by the BigQuery operator, so the logic is reviewable and testable outside Airflow. Use a partition-aware incremental query rather than rebuilding everything.

  7. 07 Step 7. Add log-based metrics and alerts

    Count failed Airflow tasks and dead-letter publishes as metrics, then alert. This puts data-platform health on the same on-call path as everything else; see Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys.

// How to verify it works

  • Publish a test message with gcloud pubsub topics publish events --message='{"id":"1","type":"test"}' and see a row in the raw table within a minute.
  • gcloud pubsub subscriptions describe events-to-bigquery shows a bigqueryConfig with no state error such as PERMISSION_DENIED.
  • Publish a message the table cannot accept and confirm it arrives on the dead-letter topic after five attempts.
  • gcloud composer environments describe <name> shows RUNNING, private endpoint enabled and the dedicated service account.
  • Trigger the DAG; the curated table gains the new row and a deliberately broken run increments the failure metric.

// Design decisions and trade-offs

  • Pub/Sub BigQuery subscriptions instead of a custom consumer, removing a service to run for plain event landing.
  • Datasets created by a module with explicit table expiration, labels and least-privilege IAM per dataset.
  • Composer environments built from a module with a dedicated service account, private IP and pinned image version.
  • A dead-letter topic on every sink so a bad message never blocks the stream.
  • Log-based metrics defined in code so data-platform health shows up in the same alerts as everything else.

// Pitfalls and lessons learned

  • The Pub/Sub service agent missing BigQuery permissions. Delivery stalls without an obvious error; check the subscription state.
  • Dead-letter permissions forgotten. The agent also needs publish on the dead-letter topic.
  • Unpartitioned raw tables, which makes every analyst query a full scan.
  • Composer running as the default compute service account with project-wide editor rights.
  • Unpinned Composer image versions, so an upgrade changes Airflow and provider versions under running DAGs.
  • Schema drift between the topic and table, causing delivery failures; use drop_unknown_fields deliberately and monitor.

// Frequently asked questions

How do I send Pub/Sub messages to BigQuery with Terraform?

Create a google_pubsub_subscription with a bigquery_config pointing at a table, and grant the Pub/Sub service agent data editor on the dataset.

Do I need Dataflow to load Pub/Sub into BigQuery?

Not for simple landing; a BigQuery subscription does it directly. Use Dataflow when you need transformation, windowing or joins before the write.

How should I secure a Cloud Composer environment?

Use private IP, a dedicated least-privilege service account, a pinned image version and restricted access to the DAG bucket.

How do I handle bad messages in a Pub/Sub BigQuery pipeline?

Configure a dead-letter topic with a max delivery attempts value, grant the service agent the needed roles and monitor the dead-letter volume.

// The outcome

Teams get a complete data path from one module call: events land in BigQuery with dead-lettering, Airflow orchestrates transformations, and logging metrics report health.

// Where to take it next

// Keep reading