Version the Image and Instance Template Contract
A Compute Engine service is released in four layers. An image carries the operating system and runtime, a template carries the machine contract, boot metadata turns that contract into a member, and an artifact carries the code. Terraform writes the middle two and only references the outer two.
An image is a versioned disk, not a running server. A pipeline produces a custom image and publishes a self link; the template stores that reference and knows nothing about how the bits were produced. Rebuilding is a pipeline run with a log and a digest, not an apply.
| Layer | Produced by | Terraform holds | Rollback unit |
|---|---|---|---|
| Image | image pipeline, outside Terraform | the exact image self link | the previous image |
| Template | apply | machine type, disks, metadata text | the previous template |
| Boot metadata | apply, from the service repository | the rendered value in state | the previous template |
| Artifact | CI build | a version name read at boot | the previous version |
What belongs in the image is a decision with a cost curve. A runtime, an agent and a hardened base belong in the image because they change rarely and slowly, while an application version belongs in the artifact because it changes every week. Moving that boundary in either direction is a deliberate trade: more in the image means fewer moving parts at boot and a heavier rebuild for every patch.
A template is immutable, so every edit is a new template. The provider states it plainly: changing any field forces a new resource. That is the right model for a service, because the previous template stays a valid rollback target, but it also means a one-word metadata edit creates an object the group has not been told about yet.
Naming is where immutability becomes visible. A fixed name collides with its replacement, so a service that edits templates regularly uses a name prefix and lets the provider generate a unique suffix. A group pinned to a fixed name cannot take the new template without destroying the old object first.
The boot disk is part of the same contract. Size, type and the delete flag are template fields, and a disk that outlives its member is a bill that survives a successful teardown. State the size explicitly rather than inheriting the image default, and decide whether the disk is disposable before the first rollout.
Machine type availability is a zone fact, not a template fact. The template is global, but a zone either stocks the shape or does not, and a large memory or accelerator shape that exists in two of three zones turns a regional group into a lopsided one. Check the shape per zone before the region enters the plan.
| Reference style | Resolved by | Plan visibility | Typical failure |
|---|---|---|---|
| exact image self link | nothing, it is fixed | the image change is visible | a rebuild nobody references |
| image family | the platform, at launch | which build is used is hidden | members booting different builds |
| fixed template name | the apply | a replacement collides with the name | an edit that cannot be applied |
| generated name prefix | the provider | every edit is a new object | templates left behind after rollback |
A family reference hides the build from the plan. Naming a family lets the platform resolve which image to use, so the plan cannot show which build a new member will boot. Pin the exact image self link, and republish that link whenever a build is meant to reach production.
A regional template narrows the blast radius. The global template is usable from any region and therefore says nothing about where its subnetwork lives, while the regional variant ties the recipe to one region and is the better default for a service with regional capacity. Whichever you choose, the group's zone list is the real availability statement.
Figure 1 follows those layers into a single template reference.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
S["Source commit"] --> B["Image build
Cloud Build or Packer"]
B --> I["Custom image
self link published"]
I --> T["Instance template
machine type, disk, metadata"]
T --> G["Regional MIG
template reference"]
G --> H["Backend service
healthy members only"]
I -.->|"family left in place"| X1["Plan cannot name the build"]
T -.->|"same name on edit"| X2["Replacement collides"]
T -.->|"shape absent in one zone"| X3["Lopsided regional capacity"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class S,G primary;
class B,I,T secondary;
class H ok;
class X1,X2,X3 danger;
Old images are the quiet half of retention. Every build leaves an image behind, and a project accumulates them faster than it accumulates templates. Keep the last few by label, delete the rest on a schedule, and never delete the image that a live template still names.
The two references are reviewed together. A template replacement appears as a create and a destroy, and the group update that points at it is a separate change in the same plan. Approving one without reading the other is how a fleet gets replaced on a Friday.
Figure 2 draws the same separation as boundaries: the pipeline produces bits, the store publishes references, and the runtime only points at them.
A rebuilt name is not a new release. Reusing a template name after a manual edit leaves state and the group disagreeing about which object is live, and the next plan offers to destroy something that is still serving traffic. Let the provider generate names, and let the reference carry the identity.
Attach a Scoped Workload Service Account
Two identities are in play, and only one of them belongs to Terraform. The deployer creates resources; the instance identity calls APIs while the workload runs. Conflating them hands every process on every member the permissions of your pipeline.
The instance identity is attached in the template. The block takes an account email and a scope list, and Google recommends a custom account with the cloud-platform scope plus permissions granted through IAM roles. Scopes are a legacy ceiling, so the binding is what actually decides access.
An access scope caps, and a role grants. The token carries both, so a workload with the right role and a scope that excludes the API still fails, which is the most common version of this mistake. Use the broad scope for a custom account and let IAM do the narrowing, so a permission change never requires a new template.
Bind additively and narrowly. A project policy resource replaces the entire policy and can delete grants made elsewhere, while a member binding adds one grant and leaves the rest alone. Give the instance account the roles its workload calls, on the smallest resource that still works.
| Identity | Acts during | Should hold | Failure when conflated |
|---|---|---|---|
| deployer | plan and apply | create and update rights on the service | runtime permissions granted to the pipeline |
| instance service account | every request | read access to the APIs it calls | one compromised member reaches every service |
| default compute account | resource creation | nothing beyond its default roles | project-wide editing power on every VM |
Boot metadata is configuration, not a vault. Any process on the member can read the metadata server, the value is stored in state, and anyone who can describe the instance can see it. It is the wrong place for a password and the right place for a parameter name.
Two metadata keys deserve an explicit decision. OS Login replaces project-wide SSH keys with IAM-controlled access, and blocking project SSH keys stops the older path from reappearing after an incident. Both are template metadata, so both are reviewed with the recipe rather than set by hand on a member.
The size limits are generous enough to hide a design problem. One value can reach 256 KB and the whole metadata set 512 KB, so a script that fits is not proof that it belongs there. Install the agent, fetch the artifact version, start the unit, and leave migrations to the release pipeline.
| Location | Readable by | Stored in state | Rotation cost |
|---|---|---|---|
| startup metadata | every process on the member | yes, in clear text | a new template |
| template label | anyone who may describe it | yes | a label update |
| Secret Manager | only the bound service account | the secret name | a new version |
| image layer | anyone who may launch the image | no | a rebuild |
Two ways to write a startup script cannot both be used. The convenience argument writes the same metadata key as a startup-script entry in the map, and the provider rejects the pair. Choose one, and keep the remaining keys small and named after their owner.
Application Default Credentials keep the chain short. Code asks the metadata server for a token and receives one scoped to the attached account, with no key file on disk. That is also why a missing binding fails at the first real request rather than during the plan.
Figure 3 follows the chain from the deployer to the authorised call, with the branches where it breaks.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
D["Deployer identity
Terraform runner"] --> SA["Workload service account
one per service"]
SA --> R["IAM member binding
narrowest resource"]
R --> T["Instance template
service_account block"]
T --> V["Member VM
no key file"]
V --> M["Metadata server
short-lived token"]
M --> A["Target API
authorised call"]
R -.->|"binding missing"| X1["403 at the first request"]
T -.->|"key file in metadata"| X2["Credential readable on host"]
R -.->|"project-wide owner"| X3["Every member over-privileged"]
T -.->|"scope too narrow"| X4["Token issued, call denied"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class D,V primary;
class SA,R,T,M secondary;
class A ok;
class X1,X2,X3,X4 danger;
One account per service, not one per environment. A shared account makes every audit question unanswerable, because a log line names the account and not the workload behind it. Separate accounts also let a compromised environment be cut off without touching the others.
Metadata changes are template changes. Because the script lives in the template, editing it creates a new template and a group update, which is a rollout that needs health evidence. Treat a boot-script fix with the same review as a code change, and expect the same replacement cost.
A key file is a permanent credential inside a temporary machine. Downloaded keys survive in images, snapshots and support bundles long after the member is gone. When a workload seems to need one, the binding is usually missing rather than the key.
Connect Managed Groups to Health and Traffic
The group owns population; the backend service owns membership. A regional group keeps a target size across the zones you name, and a backend service decides which healthy members receive requests. Neither substitutes for the other, and a failure in one looks like a failure in both.
Regional is the default for a service with an availability promise. A regional group spreads members over the zones in its distribution policy and rebuilds a lost zone's share elsewhere, while a zonal group loses that capacity with its zone. The zone list is a capacity decision, not a formality.
A named port is the join between the two resources. The backend service addresses a port by name, and the group publishes that name to its members. A missing named port produces a backend that resolves to nothing, which reads like a health problem and is a configuration one.
Autohealing and traffic health are different verdicts. The group's autohealing policy replaces a member that fails its check after an initial delay, while the backend service uses its own check to admit traffic. Point both at the same endpoint, so a member is never replaced for a reason traffic never saw.
| Signal | Owner | Default | Wrong value looks like |
|---|---|---|---|
| interval and timeout | health check | 5s and 5s | slow admission, or a rejected plan |
| healthy and unhealthy thresholds | health check | 2 and 2 | flapping membership |
| connection draining | backend service | 300s | resets when a member leaves |
| named port | instance group manager | none | a backend with nothing to address |
| autoscaler cooldown | regional autoscaler | 60s | oscillation during boot |
| target size | group or autoscaler | 0 on the group | the two resources overwrite each other |
Health check defaults are fast and shallow. Five-second interval, five-second timeout, two successes and two failures are the defaults, and a timeout longer than the interval is rejected outright. That rejection is useful: a slow check that never converges is a worse failure than a refused plan.
Draining belongs to the backend service. The connection draining timeout defaults to 300 seconds and covers requests already in flight when a member leaves. Set it above your slowest request, and remember that a keep-alive connection can carry new requests past the moment you expected.
Autoscaling is a separate resource with its own floor. A regional autoscaler reads a signal such as CPU utilisation and moves the target size between minimum and maximum, while a target size written on the group fights it. Set the minimum from the zones you must survive, and the maximum from approved quota.
The backend decides when a member is full. A utilisation target sets the point at which the balancer stops adding load, and a capacity scaler drains a member without removing it from the group. Both are backend fields, which is why moving traffic away from one member is a configuration change rather than a group resize.
The request timeout is a separate clock. The backend service's timeout bounds how long the proxy waits for a response, and it defaults to 30 seconds, which is far shorter than a slow batch endpoint. Raising it for one route is a URL map decision rather than a backend-wide one, and it has to be read alongside draining.
Cooldown is the price of a fast signal. The autoscaler waits 60 seconds by default before trusting a new member's metrics, because a booting VM reports nonsense. A cooldown shorter than boot time produces oscillation that looks like a traffic problem.
Figure 4 places the frontend chain above the backend service and the two health decisions beside the group.
The frontend is a chain, not a single resource. A global address, a forwarding rule, a target proxy, a URL map and a backend service each have exactly one owner, and a change in any of them changes the request path. Name the scheme explicitly, because a managed scheme and a classic one do not share every field.
Firewall rules are part of the load balancer. Probes arrive from Google ranges, and proxy-mode internal balancing arrives from the proxy-only subnet instead. A rule that allows the client subnet but not the probes produces members that are healthy and never join a backend.
Plan a Rollout with Capacity and Stateful Data in Mind
A template change is a service change with a rollout, not a one-line diff. The plan can create a new template and update the group while every member still runs the previous one. The release is the reference change, the update policy and the evidence that the floor held.
The update policy is where the availability promise lives. A proactive policy with a minimal action of replace and a surge budget tells the group to add before it removes. A policy with no surge and one unavailable member promises a gap on every batch.
| Change | Plan shows | Members replaced | Required action |
|---|---|---|---|
| new image on a new template | create template, update group | through the update policy | watch the healthy count per zone |
| metadata edit | create template, update group | through the update policy | read the boot output |
| machine type change | create template, update group | through the update policy | check quota and zone stock |
| new health check path | in-place backend update | none | watch admission |
| raised autoscaler minimum | in-place autoscaler update | members added | check zone balance |
| stateful disk added | in-place group update | none until the next update | confirm the delete rule |
Waiting changes what a green apply means. Left at its default, the apply returns while members are still being created, so success describes the API call rather than the fleet. Turning the wait on is slower and far more honest.
Batches are sized by the two budgets. A surge budget adds members before removal, and an unavailable budget lets the group remove before it adds; percentages scale with the fleet while fixed counts do not. Small groups need fixed counts, because a percentage of three rounds to something you did not intend.
Capacity has three separate ceilings. Regional quota for vCPUs and disks, machine type stock per zone, and the zones named in the distribution policy. A rollout that ignores any of them stalls at the batch that needed the room, usually after the first batch has already passed.
Stateful members change the replacement rule. A stateful disk survives only when the update recreates the instance rather than substituting a new one, so the update method is part of the data guarantee. Without that setting the platform keeps the name and loses the disk.
Per-instance configuration is not a template. Files that differ per member belong in a per-instance config or on a persistent disk, not in a template edit that would replace the whole fleet. The group's stateful policy is the list of what must outlive a member.
A canary is a second version in the same group. The group accepts more than one version block, each with its own template and its own share of the target size, which moves a fraction of the members without a second fleet. It is cheaper than blue/green and weaker: the canary shares the backend and the zone list with the stable version.
Rollback is a version, not a rebuild. Old templates remain addressable, so pointing the group back and running the update again is a rollback measured in minutes. That works only if the previous template was kept and the artifact it boots with still exists.
Figure 5 compares the staged update with the two ways it stalls.
Quota approval has a lead time. Regional vCPU and disk quotas are raised by request rather than by apply, so a rollout planned for tomorrow needs the request today. Put the approved ceiling in the release record next to the surge budget it constrains.
Order the release around the artifact. Publish the image, publish the artifact, create the template, update the group, then verify. Reversing the last two produces members that boot, pass a shallow check, and fail their first real request.
Measure Health During an Upgrade and Teardown
Measure the rollout, not the apply. The useful record is a timeline: template created, first member launched, first member healthy, traffic moved, last old member gone. A plan summary contains none of those moments.
Two counts must be read together. The group's member count and the backend's healthy count are different numbers, and a member count that holds while the healthy count dips is an availability event that a green apply conceals.
Per-zone counts catch what totals hide. A regional group can hold its total while one zone contributes nothing, which is exactly the failure the regional design was meant to survive. Read the distribution, not just the sum.
Teardown is part of the release. Templates, disks, addresses, health checks and firewall rules all outlive a successful rollout unless something removes them, and a stateful disk with a never-delete rule is designed to survive.
Boot evidence answers a different question than health. A member can pass a shallow probe with an old image if the probe only checks a port, so the build that actually booted is read from serial output or a boot-time label. Health says the process answers; boot evidence says which build is answering.
Deletion order is a dependency, not a preference. The backend service references the group, the forwarding rule references the address, and the group references the template, so a destroy in the wrong order fails on a reference or leaves an orphan behind. A plan shows the order; a console session does not.
| Evidence | Source | What it proves |
|---|---|---|
| template per member | the group's managed instance list | which recipe the member launched from |
| image actually booted | serial output or a boot-time label | which build reached the disk |
| healthy count over time | backend service health | whether the floor held |
| member and zone counts | group description | whether capacity stayed balanced |
| error rate through the rollout | request loop or logs | what clients experienced |
| survivors after destroy | inventory by label | what teardown still owes |
A release record should fit on one page. It holds the image self link, the template name, the artifact version, the update start and end, the lowest healthy count and the template to roll back to. A missing field is what the next incident spends its first ten minutes reconstructing.
Manual fixes are temporary by construction. A change made over an SSH session disappears at the next replacement, because the new member is built from the template. That is not a reason to avoid the fix during an incident; it is a reason to treat the next rollout as the test of whether the fix reached the image, the metadata or the artifact.
Measure Health During an Upgrade and Teardown
Status: design-only. No Google Cloud project or credential was used to produce this article, and these steps were not executed here. Versions: Terraform CLI 1.17.1, hashicorp/google 8.10.0, verified 6 November 2026.
Prerequisites. A sandbox project with billing enabled, one VPC with a subnet in each of three zones of one region, a firewall rule allowing the health-check probe ranges to the application port, permission to manage Compute, IAM and load balancing, and a budget alert on the project.
Minimal setup. One custom image, one regional template, one regional group with a floor of three, one HTTP health check, one backend service, and a request loop that closes each connection.
| Object | Lab value |
|---|---|
| Image | custom image, exact self link recorded before the change |
| Template | small shared-core machine, one boot disk, workload service account |
| Regional group | three zones, target size 3, autohealing on the health check |
| Health check | HTTP path on the application port, 5s interval, 2 thresholds |
| Update policy | proactive, replace, one surge member, zero unavailable |
| Backend service | named port, 300s draining, 30s timeout |
- Baseline. Record the healthy backend count, the template each member reports, and the error rate over five minutes. Change nothing until that baseline is boring.
- Record the rollback target. Write down the current template name and image self link before anything else moves.
- Publish a new image. Build out of band, record the self link and build id, and confirm the artifact the image expects is fetchable.
- Create the template. Apply the new template with a generated name; expect a create, and expect the group to keep its current reference.
- Plan the group change. Expect an in-place update naming the new template. A plan that replaces the group itself means an argument outside the version block changed.
- Watch the update. Note when the first new member appears and when it passes health, and keep the healthy count beside the member count every ten seconds.
- Read the request log. A short burst of errors at admission is expected. Resets as a member leaves point at draining, not at health.
- Roll back. Point the group at the previous template, run the update again, and confirm the old members return without a rebuild.
- Teardown. Destroy with a reviewed plan, then list what survived: disks, addresses, health checks, firewall rules and templates.
Expected observation. A sequence rather than a duration: template created, first member launched, first member healthy, floor held, last old member gone, rollback restored the previous template. Capture timestamps from the update and the request log so the two can be joined afterwards.
Failure checks. Members that never pass health point at the probe path, a blocked port or a missing binding. A healthy count that dips below the floor points at a surge budget too small for the zones in play. A stateful disk that disappears points at a substitution instead of a recreate. A plan that creates a second group points at a name that changed.
Cost dimensions. Instance hours including surge capacity, persistent disk per GB-month including retained stateful disks, load balancing forwarding rules, and outbound data transfer. The lab is small, but orphaned disks and reserved addresses bill until they are released.
Cleanup. Delete the backend service before the group it references, delete health checks after their last consumer, release global and regional addresses, and remove templates once no group names them. Check for disks whose delete rule kept them alive, and delete saved plans while keeping state out of Git.
References (verified 6 November 2026):
google_compute_instance_template: https://registry.terraform.io/providers/hashicorp/google/8.10.0/docs/resources/compute_instance_templategoogle_compute_region_instance_group_manager: https://registry.terraform.io/providers/hashicorp/google/8.10.0/docs/resources/compute_region_instance_group_managergoogle_compute_region_autoscaler: https://registry.terraform.io/providers/hashicorp/google/8.10.0/docs/resources/compute_region_autoscalergoogle_compute_health_check: https://registry.terraform.io/providers/hashicorp/google/8.10.0/docs/resources/compute_health_checkgoogle_compute_backend_service: https://registry.terraform.io/providers/hashicorp/google/8.10.0/docs/resources/compute_backend_service- Instance templates: https://cloud.google.com/compute/docs/instance-templates
- Regional managed instance groups: https://cloud.google.com/compute/docs/instance-groups/creating-groups-of-managed-instances
- Stateful managed instance groups: https://cloud.google.com/compute/docs/instance-groups/stateful-migs
- Health check concepts: https://cloud.google.com/load-balancing/docs/health-check-concepts
- Firewall rules for load balancing: https://cloud.google.com/load-balancing/docs/firewall-rules
Next in the Series
In Google Data Resources: Cloud Storage, Cloud SQL and Application Data, we'll explore Define storage/database retention and private access while keeping schema and bulk data separately controlled.