What You'll Learn
- 1Explain what a template freezes at build time and what stays open at launch time
- 2Compare pre-built, classic, and Flex Templates on versioning, access, and operations
- 3Build a Flex Template from a pipeline file plus metadata and launch it with gcloud
- 4Decide which parameters belong in metadata and which belong in infrastructure flags
A Beam pipeline is a graph of transforms that gets fixed the moment the job launches, so the only safe things a non-engineer can change are the values you choose to expose. A template moves that decision out of the code repository and into a launch form: the graph, the dependencies, and the container stay frozen while inputs, outputs, and window sizes stay editable. This lesson covers the three template families Google ships, the two artifacts a Flex Template needs, and the operational details that separate a demo launch from a pipeline a teammate can run without asking you for help.
What a template actually freezes
When you launch a job directly, the runner compiles whatever is in your working directory. When you launch from a template, the runner reads a specification stored in Cloud Storage and asks only for the parameters that specification declares. Your Python file, its pinned dependencies, and the entry point were resolved at build time, which is why a template job cannot drift into a library version that exists on your laptop and nowhere else.
Google publishes a bucket of maintained specifications at gs://dataflow-templates/latest/, and those are what the console's template picker lists. Anyone with the ability to create a Dataflow job in a project can launch one, because a template carries no code the launcher can edit. That is exactly the property you want when a marketing analyst needs to load a file every morning and should never have to read a Beam graph to do it.
The three families and when each wins
Most teams end up owning all three at some point, so the useful question is not which is best but which constraint you are optimising: launch simplicity, change control, or dependency freedom.
| Family | Code lives in | Who can launch | Versioning | Reach for it when |
|---|---|---|---|---|
| Pre-built (Google) | gs://dataflow-templates/ bucket | Any project with job creation rights | Google's release cadence | The connector already exists, such as Pub/Sub to BigQuery |
| Classic custom | Your bucket, JAR or Python file | Your project | File name you point at | Simple internal batch tools with few dependencies |
| Flex Template | Docker image plus metadata in your bucket | Anyone you grant | Immutable image digest | Production pipelines that must not change under you |
Classic templates stage a file and pass parameters as job arguments; they are quick to start but force every dependency into a single fat artifact and give you no way to declare parameters in a form. Flex Templates wrap the pipeline in a container, which means native libraries, pinned pip versions, and system packages all ship together, and the metadata file becomes the contract that the launch form renders from.
The two artifacts of a Flex Template
A Flex Template needs a pipeline that reads its inputs from parameters, and a metadata file that describes those parameters. Keep the pipeline's entry point free of hard-coded infrastructure: topic names, table ids, and window durations all arrive as arguments.
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import argparse, json
class Run:
@staticmethod
def run(argv=None):
known, _ = PipelineOptions().parse_known_args(argv)
parser = argparse.ArgumentParser()
parser.add_argument('--inputTopic')
parser.add_argument('--outputTable')
parser.add_argument('--windowSeconds', type=int, default=60)
args, beam_args = parser.parse_known_args(argv)
with beam.Pipeline(options=PipelineOptions(beam_args)) as p:
(
p
| 'Read' >> beam.io.ReadFromPubSub(topic=args.inputTopic)
| 'Parse' >> beam.Map(json.loads)
| 'Window' >> beam.WindowInto(
beam.window.FixedWindows(args.windowSeconds)
)
| 'Count' >> beam.CombinePerKey(count)
| 'Write' >> beam.io.WriteToBigQuery(
args.outputTable,
schema='key:STRING,count:INT64,window:TIMESTAMP',
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
)
)
{
"name": "Pub/Sub windowed count to BigQuery",
"description": "Counts events per key in fixed windows and writes the result.",
"parameters": [
{
"name": "inputTopic",
"label": "Input Pub/Sub topic",
"helpText": "projects/PROJECT/topics/TOPIC",
"isOptional": false
},
{
"name": "outputTable",
"label": "Output BigQuery table",
"helpText": "project:dataset.table",
"isOptional": false
},
{
"name": "windowSeconds",
"label": "Window size in seconds",
"helpText": "Fixed window length, defaults to 60",
"isOptional": true
}
]
}
The build command compiles the image reference and the metadata into a template specification in your bucket. After that the pipeline file is inert: relaunching the same specification always resolves the same image.
Building and launching
# One-time: stage the metadata next to the image it points at
gcloud dataflow flex-templates build gs://my-templates/pubsub-count \
--image=gcr.io/my-project/pubsub-count:1.4.0 \
--sdk-language=PYTHON \
--metadata-file=metadata.json
# Launch: every input arrives as a parameter
gcloud dataflow flex-templates run pubsub-count-$(date +%Y%m%d) \
--template-file-gcs-location=gs://my-templates/pubsub-count \
--parameters=inputTopic=projects/p/topics/events,outputTable=p:analytics.counts,windowSeconds=300 \
--region=us-central1 \
[email protected] \
--temp-location=gs://my-templates/tmp \
--worker-machine-type=n1-standard-4 \
--max-workers=10
Pin the image by digest in the build step if you need byte-for-byte reproducibility, because a mutable tag such as latest can point at different content after a rebuild. Keep the service account narrow: it needs the Dataflow worker role plus read on the topic and write on the dataset, and nothing else. Temp and staging locations must be reachable from the region you launch in, and forgetting --temp-location is the single most common cause of a template job failing in the first minute.
Parameters that do not rot
Metadata is a published interface, and every name you ship becomes something other people type. Renaming inputTopic to sourceTopic breaks every scheduled launch and every runbook that references it, so treat parameter names like an API path: add a new one, deprecate the old one, and remove it only after the audit log shows no launches. Put help text in the helpText field rather than in a wiki, since the launch form is where a user reads it. Mark anything with a sane default as optional so the form stays short.
Never put secrets in parameters. They land in the job configuration, the launch command in your shell history, and the Cloud Audit Logs. Inject credentials through the service account, and read anything application-specific from Secret Manager at runtime. Long lists such as output topics belong in a config object in GCS that the pipeline fetches, not in a comma-joined parameter that silently truncates.
Treat the specification as the release artifact and each job as an instance of it. Record the specification URI and image digest in your deployment notes so a runbook can cite exactly what ran rather than a friendly version name. That habit turns a bad deploy into a short rollback instead of an afternoon spent guessing which image the scheduler picked up.
Operating template jobs
A template job is a normal Dataflow job once running: it autoscales, it writes worker logs, and it fails on the same watermark and sharding problems any Beam job has. The operational differences are all about change. For streaming jobs you either update the running job in place, which requires the pipeline to be built for it, or you cancel and relaunch from a newer specification; the second path is simpler and is the default choice for most teams because the new image carries the fix.
Budget for three states in your runbook: a launch that never reaches JOB_STATE_RUNNING, which usually means permissions or a bad temp location; a job that runs but processes nothing, which means the source is empty or the subscription is misnamed; and a job in JOB_STATE_FAILED with a worker startup error, which points at the container image or an init script. Capture the job id at launch, wire it into your alerting, and treat a template specification change the same way you treat a code release: build it, run it in a staging project, then promote the digest.
Common Mistakes
Pointing production launches at a mutable image tag
Fix: Reference the image by digest or by an immutable release tag so a rebuild cannot change a running pipeline.
Passing credentials or connection strings as template parameters
Fix: Give the job a narrow service account and read secrets at runtime from Secret Manager instead of the launch form.
Renaming a parameter because it reads better
Fix: Add a new parameter, keep the old one optional and documented, and only remove it once the audit log shows no launches.
Best Practices
- Build the template in Cloud Build so metadata and image are produced together and tagged with the commit
- Launch through a staging project first and promote the same specification to production
- Record the specification URI and image digest on every job so you can reconstruct what ran
Key Takeaways
- A template freezes the graph, dependencies, and container at build time and exposes only declared parameters as launch inputs
- Pre-built templates are Google's code, classic templates are a staged file, Flex Templates are a container plus metadata
- Flex metadata is a published interface: help text lives there, defaults live there, and renames break scheduled launches
- Secrets never belong in parameters; the service account and Secret Manager carry credentials instead
Interview Questions
Q1: What is the difference between a classic template and a Flex Template?
A classic template stages a JAR or Python file from Cloud Storage and passes parameters as job arguments, so dependencies must fit in one artifact. A Flex Template runs a Docker image and reads a metadata file that declares its parameters, giving you pinned native dependencies, image versioning, and a launch form.
Q2: Why should a production launch pin the image by digest?
Tags are mutable, so a rebuild of the same tag can silently change the code behind a scheduled launch. Pinning the digest ties the job to the exact bytes that were tested, which makes an incident reproducible and a rollback a one-line change.
Q3: Where do you put a secret needed by a template job?
Never in the metadata or launch parameters, because they end up in job configuration and audit logs. Grant the job's service account access to Secret Manager and read the value inside the pipeline at startup.
Q4: How do you debug a template that fails one minute after launch?
Check the flex-template build logs for an image or metadata mismatch, confirm the service account has Dataflow worker plus source and sink permissions, and verify that temp and staging locations exist in the launch region. Those three account for most minute-one failures.
Q5: When is a pre-built template the right choice?
When the connector covers your source and sink and you do not need custom transforms, such as Text to BigQuery or Pub/Sub to BigQuery. It removes build and versioning work entirely; move to a Flex Template only when transformation logic or dependency pinning forces you to.