cs-image-system-gcloud-runtime-plugin
The gcloud runtime type. A runtime is where images are baked and instances
run; this package makes Google Compute Engine (GCE) one. It registers one
runtime model (GCPCloudBuilderModel), one runtime builder
(GCPCloudBuilder) and one version checker for the gcloud executable. At
load it lists the project's networks, subnetworks, routes and firewall rules
with the Compute API and checks the declared networking against them. During
a run it resolves vendor images by project and filter (or by image family),
emits the googlecompute packer source for every image baked here, bakes
and reaches instances through Identity-Aware Proxy (IAP) TCP forwarding,
answers the state query from the Compute API (images, booted images, power
states and instance identities), relabels released images, starts and stops
instances for bounded tasks, and deletes images by name. Credentials are
Application Default Credentials; the model declares none.
What it registers
The entry point is declared in pyproject.toml:
[project.entry-points."cs_image_system.plugins.runtime"]
gcloud = "cs_image_system.gcloud_runtime.main:initialize"
initialize() in main.py
returns a GcpRuntimePluginMetadata whose services map the key gcloud to
three classes and whose builders_for_models binds the model to its builder.
| Class | csis_name() |
csis_classifier() |
Registered under |
|---|---|---|---|
GCPCloudBuilderModel (gcp_runtime_models.py) |
gcloud |
VCT.CLOUD_BUILDER_MODEL |
cloud_builder_model and, because the loader re-registers cloud models as runtimes, runtime_builder_model |
GCPCloudBuilder (gcp_runtime_builders.py) |
gcloud |
VCT.RUNTIME_BUILDER |
runtime_builder |
GCPCLIVersionChecker (gcp_runtime_builders.py) |
gcloud |
VCT.VERSION_CHECKER |
version_checker |
A YAML entry selects the runtime with type: gcloud under
runtime_builders:. There are no type aliases; gcloud is the only type
key. An entry's own aliases: list gives that runtime extra names (the
fixture's gcloud-east1 also answers to gcp, google and us-east1).
The version checker is looked up by an executable's name first and its
type second, so the fixture's - name: gcloud executable in
executables.yml is parsed
by it: the checker runs gcloud --version and matches
Google Cloud SDK ([\d\.]+) on the first line of the output, so the version
checked is the SDK's (585.0.0), not the core component's date-shaped
one. The fixture requires >=500.
Present in the package but not registered as a service:
GcpProviderSpecificImage(gcp_provider_specific_image.py), reached through the builder'sprovider_specific_image_class()hook.
The GCP section of the bootstrap, through the
cs_image_system.bootstrap entry-point group: gcp = cs_image_system.gcloud_runtime.bootstrap:gcp_section. It owns the
questions and the terraform for this cloud's one-time initialisation --
the workload identity pool and GitHub provider of CI_SETUP.md 3.4, the
READ-ONLY service account and the optional WRITE one, their project
roles and workloadIdentityUser bindings, and the GCS state bucket when
the tree keeps its state in GCS and the project lacks it (versioned,
uniform access, no public access, the CI identities' object access;
managed from then on, with the AWS section's fork)
(tfmodules/bootstrap_gcp). The section renders its coverage audit for
the generated README: what it made, read, or leaves by hand and why.
This plugin ships the GCP terraform modules as package data
(gce_instance, gcp_storage_pd, gcp_storage_filestore,
gcp_storage_gcs, bootstrap_gcp, under
src/cs_image_system/gcloud_runtime/tfmodules/),
declared through the cs_image_system.modules entry point;
cs-image-system modules lists them.
The section is wanted by default where the tree declares a GCE runtime
or a gcs state backend. Its defaults come from the raw
cfg/runtime-builders.yml and cfg/state-backends.yml (a starter's
placeholders are no defaults), and every "does it already exist?"
question is a probe through gcloud as the active account (projects describe, iam workload-identity-pools [providers] describe, iam service-accounts describe, storage buckets describe): found, absent,
or -- with no credentials -- unanswerable, which --quiet refuses by
name. What exists is read as a data source and never rewritten (a
provider's condition may admit other repositories); every role and
binding is one member added. See OPERATIONS.md, "The bootstrap".
Models
GCPCloudNetworkingModel
Extends CloudNetworkingConfig in
cloud_builder.py,
which is RuntimeNetworkingModel in
runtime.py under
another name.
The full field table is CONFIGURATION 4.5. What is specific to this runtime:
network_tags(the one field it adds): GCE network tags. Firewall rules apply by target tag, so these are the closest analog to AWS security group ids. Emitted as the packer source'stagsand the instance module'snetwork_tags. A tag no firewall rule targets logs a warning at load._model_id: not an init field; the back-reference to the owning runtime model.name: empty ordefaultfalls back tonetwork.network:defaultresolves at load to the network literally nameddefault, because GCE has no default flag.subnets[].subnet_id: a subnetwork name, a full self link, or aprojects/<p>/regions/<r>/subnetworks/<n>path. The first entry withis_default: trueis the default subnet.availability_zones: read only byvalidate's zone-compatibility check; the GCE emitters use the runtime'szoneinstead.
It constrains name to be non-empty after stripping. get_subnet_id()
raises when no default subnet exists. There is no security group concept
here: security_group_ids and the like are not fields and are rejected.
GCPCloudBuilderModel
Extends CloudBuilderModel in
cloud_builder.py,
which extends RuntimeBuilderModel in
runtime.py, which
extends BuilderModel and NameTyped in
builder_model.py.
The full field table is CONFIGURATION 4.4 (the fields every runtime shares are in CONFIGURATION 4.2); the plugin's own Configuration reference below lists every field with its type and default. The keys this runtime adds, and the rules it alone enforces:
project_id: the GCP project.selfin an owner list resolves to it; without it network discovery is skipped with a warning and image resolution and bakes fail. Reported byruntime describe.zone: the zone build VMs and instances run in; the packerzone, thegoogleprovider'szone, and the scope ofinventory(),serial_console(), the boot-image probe, the power-state and identity probes andstart_instance/stop_instance.service_account_email: the service account attached to build VMs (service_account_emailin the packer source). Without it packer attaches the project's default compute service account. Nothing passes it to the instance module: an instance gets whatever the module attaches.default_disk_size: boot disk size in GB for every image baked on this runtime; wins over the image'sprimary_disk_size. A GCE instance's boot disk is exactly its image's disk.bake_preemptible: bake on a preemptible (spot) VM; a preempted bake re-runs.state_configuration: foreign key to a state backend. The storage and instance roots on this runtime resolve their backend as their own builder'sstate_configuration, else this value, else the default backend (validateresolves the bindings the same way).ssh_username: the bake's SSH user for images here that name none more specifically: step 4 of the bake-user order (CONFIGURATION 5.1.1). An entry's own user wins over it.session_mechanism:iapis the only value. The model accepts any string; the builder'ssession_mechanism()raises on anything else the first time a run orvalidateasks for it.networking: narrows the base type toGCPCloudNetworkingModeland makes it optional. Missing networking logs a warning at load.network_map,default_network,all_firewall_rules: not init fields; discovered from the project at load ({network: {"subnets": [...]}},defaultwhen a network of that name exists,{rule_name: rule}).
What this runtime does with the fields it inherits:
typeisgcloud.executable(defaultgcloudon this model) names theexecutablesentry every gcloud call on this runtime runs through (gcloud_binary()), andvalidaterefuses it undeclared.is_defaultmakes this the runtime an unqualified reference resolves to.tagsare accepted and read by nothing on this runtime: image labels are the lineage tags plus the image's own, and the instance's labels are the instance's own. For the same reasonvalidate's label-key check ("Label keys" below) does not look at the runtime's owntags.regionis thegoogleprovider'sregionand the client config'sregion.credentialsis not narrowed. The base declares no fields and forbids extra keys, socredentials:accepts nothing; clients use Application Default Credentials.default_machine_typeis the machine type when neither an OS-builder runtime entry nor an image names one, and always the instance module'smachine_type.default_image_builderis the image builder an OS-builder runtime entry withimage_builder: defaultresolves to.default_ownersis appended to every vendor-image query's owner list (through the runtime entry'sget_owners()), then mapped to projects.default_config_usernameis the bake SSH user when nothing more specific names one: step 5 of the bake-user order.ephemeral: see "Retention and the GCE cycle". The fixture'sgcloud-east1is ephemeral.retention_keep: builds kept per series when the image declares no retention.on_failure,teardown_after: runtime-level defaults for ephemeral instances.
It overrides finalize() to run update_networking() after the base
finalization, and csis_name() to return gcloud. It carries the class
attribute type = "gcloud".
Not supported: any key inside credentials: (including a service-account
key file; gcp_utils can read service_account_key_file from a session
config, but no model field carries it, so that path is unreachable from
YAML), session mechanisms other than iap, and availability_zones as a
zone selector (use zone). Because no field can reach a key file, the
load-time warning for a missing project does not suggest one: it says
that no project_id is declared on the runtime.
The builder
GCPCloudBuilder extends CloudBuilderBase in
builder_base_cloud.py,
an empty specialisation of RuntimeBuilderBase in
builder_base_runtime.py.
The runtime builder writes no files of its own: generate_items_during
defers to the base and returns nothing. Everything it contributes reaches
generated/ through the image, instance and release builders that call its
hooks. In the order a run reaches them:
| When | Hook | What it does |
|---|---|---|
| Configuration load | GCPCloudBuilderModel.finalize() |
Runs update_networking() (network discovery below). |
| Resolution | provider_specific_image_class() |
Returns GcpProviderSpecificImage. |
| Resolution | query_provider_image(subconfig) |
Finds the vendor image for one OS-builder runtime entry (image query below). Returns (image_name, owning_project, raw_result) or None. |
| Resolution | query_provider_image_by_id(subconfig, image_id) |
The image an entry pins with image_id (a GCE image NAME), searched in the entry's owner projects with the filter name = "<id>" instead of the query's filters. Same return shape; None when no owner project has an image of that name. |
| Image generation | packer_source_type() |
googlecompute. |
| Image generation | packer_source_blocks(...) |
The source "googlecompute" block for one image. |
Image generation, validate |
session_mechanism() |
iap or None; raises on any other declared value. Also read by the launch-parameter record (session), by the instance builder (no public IP under iap) and by validate's dead-end rule (a base image with no admin key AND no session mechanism). |
| Image generation | session_agent_commands(os_family) |
Installs google-guest-agent when missing (apt-get for debian/ubuntu, yum otherwise) and enables it together with sshd/ssh. Empty when the mechanism is not iap. |
| Image generation | session_verify_commands(os_family) |
Assertions that the guest agent is present and enabled. Empty when the mechanism is not iap. |
validate |
label_key_problem(key) |
Implemented by this runtime (the base returns None, because AWS tags take any key). Returns a reason when gce_label(key) does not start with a lowercase letter: GCE label keys must start with a lowercase letter; '<key>' becomes '<label>'; otherwise None. validate's check_label_keys asks it for every tag key declared on an image, instance or storage that lands on this runtime (see "Label keys" below). |
| Image generation | default_bake_user(family), bake_ssh_username(image), one_bake_user_per_chain() |
default_bake_user is packer for every family (the last step of the bake-user order). bake_ssh_username(image) is the RESOLVED user for that image, the one the packer source bakes as, and the ansible provisioner names it. one_bake_user_per_chain() is True, so validate refuses a chain whose images resolve to different users, because the guest agent removes the other-name user at first boot and aborts key provisioning. |
| Image generation | bake_finalize_commands(os_family) |
The last provisioner of every bake here: adds the build user to google-sudoers when that group exists, so the guest agent's first-boot user cleanup succeeds and metadata SSH keys get provisioned. Emitted whatever the session mechanism. |
| After a bake | build_id_from_artifact(artifact_id) |
The packer manifest's artifact_id is the image name itself; returned unchanged. |
| After a bake | retag_image(image_id, tags) |
The packer builder stamps the recorded csis_parent and csis_fingerprint back onto the image (zero-drift-report). |
| Instance verification | serial_console(name) |
Serial port 1 output of the instance, read-only. |
| Instance verification | verify_instance(name, expected_build, expect_mounts, timeout) |
Polls the serial console every 15 s until the guest agent reports the startup scripts finished (Finished running startup scripts, or the older startup-script exit status 0) or an explicit failure line appears, compares the booted image with the expected build, and counts the kernel's XFS (...): Ending clean mount lines against the declared data disks. |
| Instance operations | run_session_command(name, script, timeout) |
<declared gcloud> compute ssh <name> --project <p> --zone <z> --tunnel-through-iap --quiet --command <script> as the operator's gcloud account. Refused with declares no session_mechanism before anything runs when the runtime declares none, so the failure names the declaration instead of surfacing as IAP's problem. Used by verify instance (post-bake tests), unmount storage, the alias writer and the reachability wait. |
| Instance operations | can_query_instance_power_state(), query_instance_power_state(name) |
True; GCE's Instance.status mapped onto the system's vocabulary: PROVISIONING/STAGING starting, RUNNING running, STOPPING/SUSPENDING stopping, SUSPENDED suspended, TERMINATED stopped (on GCE it means the machine exists and can be started; a deleted instance is simply not found and answers absent), REPAIRING unknown. None means the runtime could not answer, never that the machine is off. |
| Instance operations | can_set_instance_power_state(), start_instance(name), stop_instance(name) |
True; instances.start/instances.stop, waiting on the operation, then re-reading the state. Only running_for_task calls them (a bounded task that needs a running machine, which puts it back). |
| Instance operations | can_query_instance_identity(), query_instance_identity(name) |
True; the numeric instance id and the internal hostname (a custom hostname when set, else <name>.c.<project>.internal). Feeds the generation ledger and the provider-alias writer. |
empty --runtime |
inventory() |
Instances and disks in the zone and every custom image in the project (Compute API), plus the project's buckets (gcloud storage buckets list). |
| Retention | dispose_image(build_id) |
Deletes the image named by the build id and waits for the operation. NotFound returns False (already gone). |
| State reconciliation | retag_image(image_id, tags) |
setLabels on one of the system's own images: the current labels merged with the given tags, both sides passed through gce_label(), with the image's label fingerprint. Also the hook behind lineage relabel and restamp. |
| State query | query_images(series) |
The images in the project whose csis_series label equals gce_label(<s>) for one of the series s asked about: {image_id, name, state, created, tags} (labels as tags). An empty series list keeps every image that carries a csis_series label. The state query asks for every recorded series plus every declared OS builder and image; lineage relabel asks for the series of the builds it relabels. |
| State query | can_query_instance_boot_image(), query_instance_boot_image(name) |
True; the instance's boot disk's source_image basename, or None when the instance, disk, zone or project cannot be resolved. Read-only, never fatal. |
| Release | release_commands(build_id, tags) |
Base default: none. A release on GCE is recorded and relabelled through retag_image, not through a CLI command. |
gce_name() and gce_label() in
gcp_packer_source.py
are the one place every csis name and tag is mapped to GCE's constrained
forms: names to [a-z]([-a-z0-9]*[a-z0-9])? (63 characters, prefixed i-
when they would start with a digit), labels to lowercase [a-z0-9_-].
Every hook that names a GCE resource goes through them.
Label keys
gce_label() lowercases a key and replaces what GCE cannot keep, but it
cannot invent a first letter, and GCE requires a label KEY to start with a
lowercase letter. A tag key such as 2024, -env or _x therefore
becomes a label key GCE refuses. The runtime says so through
label_key_problem(key), and validate runs check_label_keys in
validate.py over
every declared tag key that becomes a label here: an image's tags for each
runtime it bakes on, an instance's tags on its runtime, and a storage's
tags on its storage builder's runtime. A key GCE cannot take is refused,
naming who declared it:
<image|instance|storage> '<name>': tag key '<key>' on runtime <rt>: GCE label keys must start with a lowercase letter; '<key>' becomes '<label>'; rename the key
The key is never renamed silently: the operator renames it in the YAML.
Refusing the key at validate keeps GCE from refusing it at apply. A tree
validated on an older release may still carry such a key;
the stage index places the rule. Label
VALUES are not checked. The runtime's own tags are not checked because
nothing on this runtime reads them.
Credentials
GCPCloudBuilderModel.self_to_gcp_client_config() returns project,
region and zone (and credentials, which is always empty). The Compute
clients in gcp_utils.py
are built without explicit credentials, so the Google client library's
Application Default Credentials apply: gcloud auth application-default login on a workstation, GOOGLE_APPLICATION_CREDENTIALS, or the runner's
attached service account. run_session_command and inventory() shell out
to gcloud, which uses the operator's active gcloud account. Nothing in the
tree names a key.
Network discovery at load
update_networking() in
gcp_runtime_models.py
first calls resolve_project(); with no project it logs a warning and
returns, so a tree without project_id loads but cannot resolve images or
bake. With a project it calls get_network_map_and_default_network(), which
lists networks, routes, firewall rules and an aggregated subnetwork list once
each and builds:
network_map: for every network, asubnetslist of{subnet_id, self_link, region, cidr, is_public, tags, config}. GCE routes are network-scoped, so a network is public when it has a0.0.0.0/0or::/0route whose next hop isdefault-internet-gateway, and every subnetwork in it inherits that.default_network:defaultwhen a network of that name exists.all_firewall_rules: every rule by name.
Then it validates the declaration: network: default becomes the network
named default (an error when the project has none); the network must
exist; every declared subnet_id must match a subnetwork by name, full self
link, or projects/... path suffix; every network_tags entry that no
firewall rule targets logs a warning.
The image query
query_provider_image() takes one OS-builder runtime entry
(OSBuilderBaseImageBuilderSubconfig in
os_builder_runtime_config.py)
and asks it for its effective query, entry.image_query(): an
ImageQuery in the SYSTEM's vocabulary
(contract/image.py).
That query is the image-source catalog's gcloud block for
the OS builder's family (the release's layer under the tree's
cfg/image-sources*.yml), with the OS builder's own query landing on it
key by key and the runtime entry's landing on that; the publishers
declared anywhere (the OS builder's owners, this runtime's
default_owners, the entry's owners) replace the catalog's. The builder
translates it with translate_image_query() (the table below) into
projects and a Compute list() filter expression; query_image() in
gcp_utils.py resolves
the projects (resolve_projects(): self becomes the session project;
the aliases debian, ubuntu, rhel, centos, rocky, fedora,
suse, windows, cos and google become the public image projects;
AWS-only aliases and anything that is not a valid project id are dropped;
a valid project id such as almalinux-cloud is kept as is), lists every
candidate project, and returns the newest creation_timestamp with the
owning project added; with newest: false more than one match raises
ImageQueryError as ambiguous. The builder returns (name, project, raw); the base registers a GcpProviderSpecificImage in the resolved
state. validate has already refused an entry whose query uses a key this
runtime cannot translate (the EC2 particulars) or has no source at all,
and has printed every entry's query in both vocabularies.
The gcloud blocks of the release's catalog are this plugin's: it ships
them as package data,
data/image-sources.yml,
and GCPCloudBuilder.image_source_entries() reads that file. The core
merges every installed runtime's part by family, so the release catalog a
tree sees carries a gcloud block exactly when this plugin is installed.
Two families the other runtimes know are absent from the file on purpose:
Compute Engine has no public Fedora family, and its Ubuntu families are
named by release (ubuntu-2404-lts-amd64), not by major version, so a
tree declares the one it bakes (CONFIGURATION 5a.1).
Image query translation
What translate_image_query() does with each key of the system's
vocabulary (supported_query_keys() is the set of rows not marked
refused; tests/test_docs_image_sources.py
holds this table to it). The answer is {"projects": [...], "terms": {<image field>: value}, "filter": "<the list() expression>", "most_recent": bool}.
| System key | Compute Engine field | Note |
|---|---|---|
name |
name |
a glob over the image name |
family |
family |
the vendor's image family; the latest READY image of it is the match |
version |
refused | the catalog fills {version} into name or family |
architecture |
architecture |
x86_64 becomes X86_64, arm64 becomes ARM64 |
publisher |
the projects | project ids and the aliases above |
state |
status |
available becomes READY, forced when unset |
virtualization |
refused | an EC2 particular |
root_device |
refused | an EC2 particular |
tags |
labels.<key> |
one term per tag |
newest |
most_recent |
true when unset; false refuses more than one match |
native |
verbatim | each key an image field, passed as written into the expression |
When the entry declares image_id, the base's resolve step
calls query_provider_image_by_id(entry, image_id) instead. A GCE image
is named uniquely within its project, so the id is an image name and is
searched where the vendor query would search: the effective query's
publishers as the projects, and the filter name = "<id>"; a match whose
status is not READY is refused by name (GCP runtime <rt>: pinned image '<id>' is <status>, not READY; a bake from it would fail).
The owning project is read from the result as for the query (else
self). No match returns None, and the base stops resolution with OS builder <name>: image_id '<id>' on runtime <rt> is not known to the provider. Pinning makes the base bake reproducible: the same vendor image
every time, where the query takes the newest match (a vendor family
publishes a new image often).
GcpProviderSpecificImage.get_query_assets() describes the image as a
generic query (filters = { name = "<name>" } plus owners when resolved;
when deferred, an ImageQuery for <pattern>* from self, translated
and quoted: owners = ["self"], filters = { name = "<pattern>*" },
most_recent). The packer source does not use these assets: GCE's image
families are the series, so googlecompute_source() writes source_image
(a resolved or pinned parent) or source_image_family (a deferred parent)
directly.
tests/test_gcp_utils.py and tests/test_gcp_provider_specific_image.py pin the translation, the project resolution, the newest-wins rule and the asset shapes without network access.
Image families
Every bake sets image_family = gce_name(<series>), so "the latest build of
series X" is GCE's own source_image_family = X lookup. A pinned parent
bakes from source_image = gce_name(<build id>); the build id is the image
name. query_images() reads the csis_series label rather than the family
so the state query compares the same facts on both clouds, and it filters
on that label: only images whose csis_series equals
gce_label(<series>) for a series it was asked about come back (the label
carries the sanitised form, so the comparison is made in that form).
IAP
With session_mechanism: iap the packer source gets use_iap = true and
iap_tunnel_launch_wait = 120, so packer reaches the build VM through the
IAP tunnel instead of its external address; the ephemeral external IP stays
for package egress only. run_session_command tunnels the same way, and the
GCE instance builder launches instances with public_ip = false. The
operator prerequisites are outside the tree: a firewall rule allowing
35.235.240.0/20 to port 22 and roles/iap.tunnelResourceAccessor for the
account that opens tunnels. The bake installs google-guest-agent so
metadata SSH keys are provisioned at first boot.
The state query and instance hooks
query_images, query_instance_boot_image, query_instance_power_state,
query_instance_identity, inventory, serial_console, retag_image,
dispose_image, start_instance and stop_instance use compute_v1
clients built from the session config. The state query in
state_query.py reads
query_images to classify missing, foreign and changed images
(asking for every recorded series and every declared OS builder and image,
so an image labelled with a series the tree neither records nor declares
is not listed on GCE), asks
query_instance_boot_image because can_query_instance_boot_image() is
True, and asks query_instance_power_state before calling a silent boot
probe "unavailable": a stopped machine is a note, not drift.
verify_instance is the deferred verification step of the instance
lifecycle, run inside running_for_task (a stopped instance is started for
the check and stopped again afterwards; one that cannot be started is a
SKIP, recorded as such). inventory() feeds empty --runtime, which
subtracts the declared storages' cloud names and the released builds and
reports what is left.
Retention and the GCE cycle
The closing retention lifecycle in
retention.py runs
dispose image --retention at execution time. For each series on this
runtime the number of builds kept is, in order: 0 when the runtime is
ephemeral, the image's retention.keep, the runtime's retention_keep,
else everything. Builds beyond that are disposed through dispose_image(),
except released builds and builds an instance is pinned to or was launched
from, which are reported as retention debt and kept. Declared storages are
never touched by retention.
The fixture's gcloud-east1 declares ephemeral: true, and this is the
GCE cycle: a run bakes its images, launches its ephemeral instance, verifies
it from the serial console, tears it down, and the closing retention step
disposes of every image baked on the runtime. What persists across runs is
the declared storages (a persistent disk and a bucket in the fixture) and
any released build. empty --runtime gcloud-east1 proves the runtime is in
that state afterwards.
Cost posture
A successful run on an ephemeral GCE runtime leaves standing: the declared
storages and any released build. It may also leave standing: a
non-ephemeral instance, and an ephemeral instance whose verification failed
under on_failure: keep (teardown_after lets a later run tear it down).
bake_preemptible: true bakes on spot VMs; default_disk_size fixes the
boot disk of every image, and therefore of every instance, at a small size.
On a non-ephemeral GCE runtime the AWS rules apply: images stand until
retention or an explicit dispose image removes them.
Emission
The plugin's output is visible in the golden emission under tests/fixtures/v2_golden/generated.
- pckr-gce-ans-image-generation-source-basic-rh-10-block-000.pkr.hcl:
the
source "googlecompute"block written bygooglecompute_source():project_id,zone,source_imageandsource_image_project_id(a resolved vendor image and its project),image_name(gce_nameof the final name),image_family(the series),image_labels(the merged lineage tags, sanitised),machine_type(the runtime entry's, else the runtime default),service_account_email,use_iapandiap_tunnel_launch_wait(the mechanism isiap),preemptible,disk_size(fromlineage.bake_disk_size, the one rule the input fingerprint also hashes; here the runtime'sdefault_disk_size),ssh_usernameandsubnetwork(the default subnet).networkis emitted only when it resolves to a non-default name, andtagsonly whennetwork_tagsare declared. - pckr-gce-ans-image-generation-block-000-build.pkr.hcl:
the
# debug session mechanism (iap)shell provisioner (session_agent_commands), the# verify: guest agent baked for IAP sessionslines inside the in-bake verification (session_verify_commands), and the closing# runtime bake finalization (gcloud-east1)provisioner (bake_finalize_commands). Thegooglecomputeentry in the neighbouring-plugins.pkr.hclcomes from the image builder'srequired_plugins. - tofu-gce-instance-generation.tf
and
tofu-gce-instance-generation-instance-gce_test.tf:
written by the GCE instance plugin from this model.
provider "google" { project, region, zone, alias }; the instance module'smachine_type(the runtime default),zone,subnetwork(the default subnet),image_family(the series),public_ip = falseunderiapand, when declared,network_tags. The.tfbackend.hclbeside them is an S3 backend written by the state-backend plugin; GCE roots keep their state there. - Runtime facts:
cs-image-system runtime describe gcloud-east1(runtime_facts.py) reportsruntime,type,project_id,zone,region,default_machine_type,ephemeral,retention_keep, theimages,storages,instancesandephemeral_instancesdeclared on it, thebuildersbound to it and itsemissiondirectories;empty --runtime gcloud-east1adds the liveinventoryand theleftovers. Commands, not files.
Example configuration
From tests/fixtures/config/cfg/runtime-builders.yml:
runtime_builders:
- name: gcloud-east1
aliases:
- gcp
- google
- us-east1
type: gcloud
# Credentials come from the environment only (Application Default
# Credentials or GOOGLE_APPLICATION_CREDENTIALS); nothing is declared here.
project_id: csis-sandbox
zone: us-east1-b
session_mechanism: iap
# build VMs run as the least-privilege runner account (the packer source
# carries it; the instance module attaches no service account)
service_account_email: csis-runner@csis-sandbox.iam.gserviceaccount.com
# bake disk (= every instance's boot disk) at the vendor image's 10 GB floor
default_disk_size: 10
bake_preemptible: true
# nothing baked here survives a successful run; declared storages persist
ephemeral: true
tags:
Project: csis-sandbox
Environment: Development
region: us-east1
default_machine_type: e2-micro
default_image_builder: pckr-gce-ans
networking:
network: default
subnets:
- name: subnet1
subnet_id: projects/csis-sandbox/regions/us-east1/subnetworks/default
is_default: true
public: true
Prerequisites and integration
Everything below exists outside the system; the plugin creates none of it and generates no IAM change. For each item: how the plugin finds it.
A GCP project with the Compute Engine API enabled. Found through
project_id on the runtime entry; it is the project of every Compute
client call, the packer source's project_id, the google provider's
project and the project self resolves to in an owner list. Without it
the tree loads with a warning and nothing that touches GCE works. The
Compute API must be enabled for the project: the first thing the plugin
does with it is list its networks at load.
Application Default Credentials (ADC) for a principal that can act in
that project. The model declares no credentials (credentials: accepts
no key), so every compute_v1 client is built with no explicit credentials
and the Google auth library's default chain applies, in its order:
GOOGLE_APPLICATION_CREDENTIALS naming a credentials file, else
~/.config/gcloud/application_default_credentials.json (written by gcloud auth application-default login), else the metadata server of an attached
service account. The operator's form, from
docs/OPERATIONS.md ("Credentials and sessions"):
gcloud auth application-default login --impersonate-service-account=csis-runner@<project>.iam.gserviceaccount.com
which needs roles/iam.serviceAccountTokenCreator on the runner for the
operator's own Google user. cs-image-system preflight and every run and
state print one session: line for it; the check is this plugin's own
session_status hook (session.py),
which reports whether the ADC file exists at the same path (presence
only: an impersonated or authorized-user ADC refreshes itself, so no
expiry is readable) and names gcloud auth application-default login as
the renew command; the core prints what the hook answers and reads no
credential file itself. A gcs state backend reaches the same reading
through this runtime's class, so a tree with the backend alone is
preflighted too. In CI the
google-github-actions/auth action turns GCP_WORKLOAD_IDENTITY_PROVIDER
and GCP_SERVICE_ACCOUNT into ADC (read-only in CI: the GCE runtime is out
of CI by the cost decision, and the perform job only records and guards).
What that principal must be allowed to do, by hook: list networks, routes,
firewalls and subnetworks (load); list and get images in the project and in
the public image projects the owner aliases name (resolve, the state
query, lineage relabel, empty); getFromFamily (a family query);
images.delete (retention, dispose image) and images.setLabels (the
post-bake retag, relabel, restamp); instances.get, instances.list,
instances.getSerialPortOutput, instances.start, instances.stop and
disks.get/disks.list in the zone (verification, the state query,
empty, the power-state and identity probes). Bakes run as this principal
too: packer creates the build VM and the image, and attaching
service_account_email to the build VM needs roles/iam.serviceAccountUser
on that account (a least-privilege runner cannot actAs the default
compute service account, which is why the field exists).
A service account for build VMs. Optional. Found through
service_account_email; emitted into the packer source only. Without it
packer attaches the project's default compute service account.
A VPC network and a subnetwork in the project. Found through
networking.network (default means the network named default; the
project must have one) and networking.subnets[].subnet_id; both are
checked against the project at every load, so a load needs the API and the
credentials above even for a dry run or validate. The subnetwork's region
should be the runtime's region and contain the runtime's zone; the
plugin does not check that, GCE refuses the VM at bake or launch if it is
wrong. Under iap instances get no public IP, so anything an instance must
reach on the internet needs a route the operator provides (the bake VM keeps
an ephemeral external IP for package egress).
IAP TCP forwarding, when session_mechanism: iap. Three things the
tree never creates, from OPERATIONS.md ("IAP sessions on GCE"): a firewall
rule allowing tcp:22 from 35.235.240.0/20 on the instances' network
(network_tags on the runtime select tagged rules; a tag no rule targets
is warned about at load); roles/iap.tunnelResourceAccessor for the runner
service account, because bakes tunnel too (use_iap = true); and the same
role for each operator's own Google user, because run_session_command
runs gcloud compute ssh --tunnel-through-iap as the operator's active
gcloud account, not as the impersonated ADC. The operator's SSH key must be
agent-loaded or passphrase-less: nothing in a run can prompt. The images
bake the Google guest agent so metadata SSH keys
are provisioned at first boot; the base image's package manager must be
able to install google-guest-agent (apt-get on debian/ubuntu,
yum elsewhere; the vendor images carry it already).
The gcloud CLI. Two hooks shell out to it: run_session_command
(gcloud compute ssh) and inventory() (gcloud storage buckets list,
so empty --runtime needs storage.buckets.list for the gcloud account).
Both run the binary of the executables entry the runtime's
executable names (default gcloud), so the entry must be declared:
validate
refuses the runtime without it. Its version is checked
when it is declared under executables: with name: gcloud (the checker
is registered under that name): the fixture declares
binary: /usr/local/bin/gcloud and version: ">=500", the Google Cloud
SDK version; validate and every run refuse when the binary is missing,
the version cannot be parsed from gcloud --version, or it is below the
floor. Packer's googlecompute plugin is a prerequisite of the packer
image builder (required_plugins on the packer-gce builder), not of this
package.
A live AWS session as well. The GCE roots keep their terraform state
in the S3 backend by standing decision, and the tree's AWS runtimes
validate their networking at the same load, so a GCE lifecycle, empty --runtime gcloud-east1 and every configuration load need the AWS
profile's session too (an expired SSO session stops GCE work even with
GCP fully authenticated). See
docs/OPERATIONS.md for the profile.
Python dependencies, from pyproject.toml:
google-cloud-compute>=1.49, google-api-core>=2.31, google-auth>=2.55,
python-hcl2>=8.1, pydantic>=2.13, and the system's own
cs-image-system-contract, cs-image-system-base and
cs-image-system-hashicorp-utils at the same version. Python 3.13 or
later.
Environment variables the plugin or its checks read: GOOGLE_APPLICATION_CREDENTIALS
(optional; the ADC file), and in CI GCP_WORKLOAD_IDENTITY_PROVIDER and
GCP_SERVICE_ACCOUNT (read by the auth action, not by the plugin). The
preflight also refuses any GOOGLE_* or CLOUDSDK_* variable that is set
but empty: those are the prefixes this plugin declares through
credential_environment_prefixes().
Configuration reference
The YAML this plugin owns is one entry of runtime_builders: in
cfg/runtime-builders.yml with type: gcloud; the manual's section is
docs/CONFIGURATION.md 4.4. Every field the
plugin's model accepts, and who reads it:
| Field | Type | Default | Meaning |
|---|---|---|---|
name |
str | required | the runtime's name; other builders name it through runtime:; the # runtime bake finalization (<name>) provisioner carries it |
type |
str | required | gcloud |
description |
str or null | null | free text; accepted, not read by this plugin |
aliases |
list[str] | [] |
extra names the runtime answers to |
executable |
str or null | gcloud |
the executables entry whose binary every gcloud call on this runtime runs (the session command, inventory(), the tf-gcp storage lookups and generated scripts); validate refuses a name that is not declared |
is_default |
bool | false | the runtime an unqualified runtime reference resolves to |
config |
mapping | {} |
free-form; accepted, not read |
gitignore |
list[str] | [] |
accepted, not read by this plugin |
tags |
mapping[str, str] | {} |
accepted, not read: no image label, instance label or storage label comes from the runtime's tags |
region |
str | required | the google provider's region; the client config's region |
project_id |
str or null | null | the project (see above); runtime describe reports it |
zone |
str or null | null | the zone of build VMs and instances and the scope of every zonal query; runtime describe reports it |
service_account_email |
str or null | null | the packer source's service_account_email; instances are not given it |
default_disk_size |
int or null | null | the packer source's disk_size in GB, the first step of lineage.bake_disk_size; null falls back, for a base image, to its OS builder entry's default_primary_disk_size and then the OS builder's, and for an instance image to its primary_disk_size |
bake_preemptible |
bool | false | preemptible = true on the packer source |
state_configuration |
str | default |
the state backend rung between a root's own and the default backend |
ssh_username |
str | default |
the bake's ssh user for images that name none more specifically (step 4 of the bake-user order, CONFIGURATION 5.1.1); with nothing named anywhere, packer |
session_mechanism |
str or null | null | iap, or nothing; any other string is refused by the builder when first read |
default_machine_type |
str | required | the bake's machine_type when the OS-builder runtime entry names none, and always the instance module's machine_type |
default_image_builder |
str | default |
the image builder an OS-builder runtime entry with image_builder: default resolves to |
default_owners |
list[str] or null | null | extra owners for every vendor-image query on this runtime, resolved to projects |
credentials |
mapping | {} |
must be empty; any key is a validation error |
default_config_username |
str or null | null | the bake ssh user when no image entry, OS entry, config_username or runtime ssh_username names one |
ephemeral |
bool | false | every image baked here is disposed by the closing retention lifecycle |
retention_keep |
int or null | null | builds kept per series when the image declares no retention; null keeps all |
on_failure |
str or null | null | ephemeral default: keep or teardown |
teardown_after |
str or null | null | ephemeral default: <number> followed by m, h or d |
networking |
mapping or null | null | below; null loads with a warning and bakes and instances then emit no subnetwork |
networking:
| Field | Type | Default | Meaning |
|---|---|---|---|
name |
str | the network | a label; must not be empty after stripping |
network |
str | default |
the network name; default becomes the network literally named default at load |
subnets |
list | required, at least one, one is_default: true |
see below |
availability_zones |
list | [] |
{name, is_default}; only validate's zone-compatibility check reads the default one |
network_tags |
list[str] | [] |
the packer source's tags and the instance module's network_tags |
networking.subnets[]:
| Field | Type | Default | Meaning |
|---|---|---|---|
name |
str | the subnet id | label |
subnet_id |
str | required | a subnetwork name, self link, or projects/<p>/regions/<r>/subnetworks/<n> path; checked against the project at load; the default one is the packer source's and the instance module's subnetwork |
is_default |
bool | false | the subnet bakes and instances use |
public |
bool | false | accepted, not read (the plugin discovers publicness from the routes) |
cidr |
str or null | null | accepted, not read |
availability_zone |
str or null | null | the zone validate's compatibility check attributes to the runtime when no default availability zone is declared |
config |
mapping | {} |
accepted, not read |
Fields the plugin reads from YAML it does not own:
| Where | Field | Read by |
|---|---|---|
the OS builder's runtime entry (os_builders[].runtimes[]) |
owners, query.filters, query.owners |
the image query |
| the same entry | image_id |
a GCE image name that replaces the query's filters; searched in the entry's owner projects |
| the same entry | default_primary_disk_size |
a base image's disk_size when the runtime declares no default_disk_size |
| the same entry | machine_type, default_machine_type |
the packer source's machine_type, before the runtime default |
| the same entry | ssh_username |
the packer source's ssh_username and the ansible provisioner's user, for this OS and every image built on it, whatever the runtime declares |
| the image | primary_disk_size |
an instance image's disk_size when the runtime declares no default_disk_size (a base image's is its entry's default_primary_disk_size, else the OS builder's) |
| the image | source_image, parent_policy, the pin |
source_image (pinned or resolved) or source_image_family (deferred) |
cfg/executables.yml |
the gcloud entry's binary and version |
the version checker |
| the instance | runtime, image, storages, tags |
the GCE instance plugin, which reads zone, default_machine_type, networking and session_mechanism from this model |
Not in the model, and refused at load because unknown keys are errors:
account_id, security_group_ids, session_instance_profile,
iam_instance_profile, ena_support, sriov_support, runtime_classifier,
and any key inside credentials:.
Variations
session_mechanism: iapvs unset. Withiapthe packer source getsuse_iap = trueandiap_tunnel_launch_wait = 120, the bake gains the guest-agent install provisioner and the guest-agent assertions in its in-bake verification, the instance module getspublic_ip = false, the launch record'ssessionisiap, andrun_session_commandworks. Unset, the bake reaches the build VM over its external IP on tcp:22 (which needs a firewall rule the operator owns), instances keep a public IP, no agent is installed or asserted,run_session_commandstill runsgcloud compute ssh --tunnel-through-iap(it does not check the mechanism, so it fails without the IAP wiring), andvalidaterefuses a base image on this runtime that also declares no admin public key (no debug path). The finalize provisioner is emitted either way.ephemeral: truevsfalse. Ephemeral: the closing retention step disposes every build baked here that is not released, pinned or launched from, whateverretention_keepor the images'retentionsay;empty --runtimethen expects no custom image but released ones. Durable: builds stand untilretention.keep,retention_keepor an explicitdispose image.- Pinned vs deferred vs resolved parent. A pinned parent bakes from
source_image = gce_name(<build id>); a resolved vendor image fromsource_image = <name>plussource_image_project_id = ["<project>"](omitted when the owner isselfor unset); a deferred parent (built earlier in the run or by a previous one) fromsource_image_family = gce_name(<series>), which GCE resolves to the newest image of the family.parent_policy: followmoves the pin after the bake and the post-bake retag writes the resolved parent onto the image. default_disk_sizeset vs null. The packer source'sdisk_sizeislineage.bake_disk_size, the rule the input fingerprint also hashes. Set: every image here bakes at that size and everything else is ignored. Null: a base image takes its OS builder entry'sdefault_primary_disk_sizefor this runtime when declared, else the OS builder'sdefault_primary_disk_size(200 GB unset); an instance image takes its ownprimary_disk_size.- A queried vs a pinned vendor image. Without
image_idon the OS builder's entry, resolution runs the filter query and takes the newest match, so the next base bake may start from a newer vendor image. Withimage_idthat one image name is looked up in the entry's owner projects; the id is part of the fingerprint's vendor source. ssh_usernameset vsdefault. Either way the packer source and the ansible provisioner name the same user, the one the bake-user order resolves: an entry's user wins over this field, this field over the runtime'sdefault_config_username, and with nothing named anywhere it ispacker.network: defaultvs a name.defaultis replaced at load by the network nameddefaultand the packer source emits nonetworkline; a named network is checked to exist and emitted asnetwork.network_tagsdeclared vs empty. Declared:tags = [...]on the packer source,network_tagson the instance module, a load-time warning per tag no firewall rule targets. Empty: neither line is emitted.- Owner aliases vs project ids vs AWS-only owners.
selfbecomesproject_id; distro aliases become the public image projects; a valid project id is used as is;amazon,aws-marketplace,aws-backup-vaultand anything that cannot be a project id (an AWS account number) are dropped, so a shared OS-builder query works on both clouds. - A query with keys of another cloud.
root_device_type,virtualization_type,block_device_mapping.*and the other keys outsidesupported_query_keys()cannot be translated for GCE:validaterefuses the entry and names the key, and the translation raisesValueErrorif it is ever reached; only owner aliases are dropped, never keys. (The plugin once carried a list of the other cloud's keys in order to drop them; nothing read it, and it is gone.) A base image shared by both clouds therefore keeps its query to the keys both runtimes translate (the table above). state: availablevs anything else.availablemaps tostatus = "READY", which is also forced when no status is given;pending/failedmap toPENDING/FAILED; another value is upper-cased as given.bake_preemptible: truevsfalse. True emitspreemptible = true; a preempted bake fails and is re-run by the next run (nothing is recorded for it). False emits nothing.project_idset vs null. Null: the load warns and skips network discovery and validation;resolvethen fails withOwner 'self' requires a project ...and every Compute hook raisesno project .... The warning names the missingproject_id: no field of this runtime can declare a service account key file, and the project is never read from the Application Default Credentials.- A tag key that starts with a lowercase letter vs one that does not.
A key whose
gce_labelform starts witha-z(Projectbecomesproject) passes and is emitted as a label. A key whose label form starts with anything else (2024,-env,_x) on an image, instance or storage that lands on this runtime is refused byvalidate(check_label_keys); the same key on an AWS runtime passes, because the baselabel_key_problemanswersNonethere. query_imageswith series vs with none. Given series, only images whosecsis_serieslabel is one of them (ingce_labelform) come back; given an empty list, every csis-labelled image in the project does.- Dry run vs real run. The plugin itself does not read the flag. A dry
run still loads (so network discovery still calls the API), still
resolves vendor images (the
resolvephase queries the image projects), and still emits the packer source and the terraform arguments; nothing is baked, verified, disposed or relabelled because the runner scripts are enumerated, not executed.dispose imageunder--dry-runprints its plan and calls no hook;lineage relabelis dry by default. - Apply flag on vs off. With
apply_instances: [gcloud-east1](or--apply-runtime gcloud-east1) the instance root applies, the launch is recorded, the verification runs,mark_launchedfires, the generation ledger asksquery_instance_identityand the alias writer asks it again. Off, the root plans and gates only and none of the instance hooks run. --only-runtimeanother runtime. No GCE image bakes and no GCE root is generated or planned (a run scoped away from this runtime cannot fail on its family lookup); retention disposes within the scoped runtime only.- A stopped instance.
TERMINATEDmaps tostopped; the state query writes anoteinstead of anunavailableline,verify instancestarts the machine for the check and stops it again,verify loginand the alias writer skip it, and nothing else touches its power state. - Encrypted vs clear values. The plugin reads no encrypted value: every
field it owns is a name, an id or a number. An
ENC[age:...]marker in one of them would reach the API as the literal marker.
What it tests and verifies
The plugin also tells the public-safety scan the shape of its own
secret: secret_patterns() declares gcp-service-account (a
private_key_id with a long hex value, the mark of a service-account key
file; the key body is a PEM block the scan refuses on its own), so the
core's scan names no cloud and still knows this one's keys.
At load (pydantic, then finalize()). Unknown keys anywhere in the
entry are refused with the field path (extra="forbid"); credentials:
with any key is refused; a networking block must have a non-empty name
and network, at least one subnet and one is_default: true; a runtime
must declare default_machine_type. Then update_networking(): with a
project it calls the Compute API and refuses the load (a ValueError; the
CLI exits 1 for any command that loads the tree, validate included) when
network: default names nothing, the network is absent from the project,
or a subnet_id matches no subnetwork of that network; it logs a warning
per network tag no firewall rule targets, a warning when networking is
absent, and a warning when no project can be resolved. The verdict lands
in the log; the discovered network_map, default_network and
all_firewall_rules stay on the model for the emitters. The test suite
stubs get_network_map_and_default_network with the fixture's own subnet
ids (see tests/harness.py), so no test reaches the API.
At validate. The gcloud executable's binary exists and its SDK
version satisfies the declared requirement (one INFO line names every
version found; a failure names the tool); session_mechanism() is asked
for the dead-end rule, so an unsupported value surfaces here as a
ValueError; the zone-compatibility check reads networking's default
availability zone or the default subnet's availability_zone against the
instances and zonal storages on the runtime; the state-location check
resolves each root's backend through state_configuration; and
check_label_keys asks label_key_problem about every tag key declared on
an image baked here, an instance on this runtime and a storage whose
builder's runtime is this one, refusing a key whose label form does not
start with a lowercase letter. Every failure is one line naming the
object, and validate exits 1.
At generation. session_mechanism() again (the packer provisioners,
the instance builder, the launch record). The packer source is emitted
with the sanitised names; the golden emission under
tests/fixtures/v2_golden pins its exact shape, and just test fails on
any drift of it. test_gcp_runtime.py asserts the emitted commands: the
finalize provisioner is the last one of every GCE bake, IAP runtimes emit
use_iap and the tunnel wait and non-IAP ones do not, the disk size comes
from the runtime, the device name and the mounted by-id path agree.
test_gce_cycle.py pins that bake_preemptible lands on the source and
that retag_image merges the lineage truth into the labels. The package's
own tests pin the query remap and project resolution.
In the bake (packer, on the build VM). The in-bake verification
provisioner runs session_verify_commands under set -e: the guest agent
binary exists and the unit is enabled; a failed assertion fails the bake
and packer deletes the build VM. The finalize provisioner runs last and is
tolerant (|| true).
After a bake. The packer builder records the build from the manifest
(build_id_from_artifact returns the image name) and calls retag_image
to stamp csis_parent and csis_fingerprint from the record; the labels
and the record then agree, which the state query later checks.
After the instance apply (verification). verify instance <name>
runs inside running_for_task; the hook polls the serial console until
the startup scripts report completion, checks the booted image against the
pin or launch record (or, for an image built this run, against the lineage
records of the instance's series on this runtime), counts clean XFS mounts
against the declared data disks, and then runs the image's declared
post-bake tests over run_session_command. The verdict lands in
meta-state/verifications.yaml (ok, checks, the last 20 serial
console lines mentioning startup, XFS or
google_metadata_script_runner as evidence), post-bake results in
meta-state/image-tests.yaml, one verify <name>: <check>: ok|FAILED -- <detail> log line per check, and a failed verdict raises
VerificationFailed, which stops the runner with the instance standing
(on_failure: keep) or after its teardown (teardown); the run exits 1.
A stopped instance that cannot be started is recorded as skipped with no
verdict.
After the apply (generations and aliases). query_instance_identity
gives the numeric instance id that defines the instance's generation in
meta-state/instance-state.yaml; the alias writer reads it again, waits
until run_session_command answers, and writes the AltNames over the same
session (log lines now also answers to [...] or a WARNING/ERROR
naming why not).
In the state query. query_images lists the images whose
csis_series label is gce_label of a series the query asked about (the
recorded series and the declared OS builders and images); the base
classifies missing (recorded, not found),
foreign (labelled, not recorded) and changed (labels disagree with the
record) images. query_instance_boot_image compares a pinned instance's
booted image with its pin (changed, or a note when a replacement is
pending) and finds standing ephemerals; query_instance_power_state turns
a stopped machine into a note. Any hook that raises becomes an
unavailable: line naming the label and the error, never a claim. The
report is generated/state-report.json (run-local) and the log;
state query --strict exits 1 on any drift but stale.
In empty --runtime. inventory() is subtracted by the declared
storages' cloud names and the released builds; any leftover instance,
image, disk or bucket is printed and the command exits 1; a hook that
cannot answer exits 2.
In retention and dispose image. dispose_image reports
deleted=True|False per build in the log (False when GCE already had no
such image); the lineage record is dropped either way.
tests/test_bootstrap_gcp.py holds the bootstrap's GCP section: the
entry point and the tree-derived gates (a GCE-only tree's quiet interview
asks nothing of AWS), placeholders and an unaskable project refused by
name, a fresh project getting the guide's pool, provider and accounts, an
existing shared provider read as it stands and deciding which attribute
the bindings name, the by-hand note when its condition does not name
this repository, the module held to the guide's attribute mapping and to
single-member grants only, and a real tofu validate.
When it fails
Incidents that have happened, with their cause and fix, are recorded on INCIDENTS.md; what follows keeps each failure's symptom, its meaning and what to do.
Failures by symptom: what each means and what to do.
instances/<name>: stopped; its pinned build ... still stand ...as anotein the state query. The operator stopped the machine. The plugin maps GCE'sTERMINATEDtostopped(the machine is not deleted: a deleted instance isnot foundand maps toabsent), and the query asks the power state before calling a silent boot probe unavailable, so the records never describe a machine that is not there. Nothing to do; a stopped machine is the operator's decision.Script disconnected unexpectedlyat the last scriptlet of the security-update transaction. A GCE base bake over the IAP tunnel can die as the OS-update transaction closes (pam,dbus-broker,libssh,curl,python3...); packer cleans its build VM and nothing is left on GCE. It is transient: look at packer's log in the bake's block directory and retry the bake alone (run base-image --only basic-rh-10@gcloud-east1). If it recurs, the watch item is packer'sexpect_disconnector a pause on the OS-update provisioner of IAP runtimes.family/imgfile-basic-daskreturned 404 at the GCE instance plan. The instance root's module resolves a deferred image throughdata "google_compute_image" { family = ... }, and the family is empty because retention disposed every GCE image. A run scoped to one runtime (--only-runtime, or--apply-runtimeimplying it) generates and plans no other runtime's root, so a run scoped elsewhere cannot meet this; in an unscoped run, bake the series first.read_passphrase: can't open /dev/tty. The operator'sgoogle_compute_enginekey is passphrase-protected and the session hook (gcloud compute ssh, non-interactive) cannot prompt, so everyrun_session_commandfails. Use an agent-loaded or passphrase-less key (the guest agent re-provisions the project'sssh-keysmetadata within seconds of the change).changeddrift:fingerprint differson a follow image. Aparent_policy: followimage baked in the same run as its parent gets its labels from packer at generation time (parentseries:..., a placeholder fingerprint) and its lineage record after the bake, which is whyretag_imagedoessetLabelsafter every bake; the strict preflight refuses the next run while labels and record disagree. For images already standing:lineage relabel --runtime <rt>(just cloud-relabel <rt> no; dry by default) re-labels every recorded build whose labels disagree with its record.4047: Failed to lookup instanceand an SSH timeout against a healthy build VM. A bake that follows another build in the same run hits IAP's instance-lookup lag for longer than packer's default 30 s tunnel wait (the serial console shows sshd up in 30 s), which is why IAP bakes setiap_tunnel_launch_wait = 120. If it recurs,PACKER_LOG=1shows the tunnel retries; the wait is a constant ingcp_packer_source.py.No valid credential sources found ... backend s3 ... the SSO session has expiredat the GCE instance plan. The AWS session lapsed; the GCE roots' state is in S3 and every load validates the AWS runtimes' networking. Renew the AWS session (aws sso login --profile <p>) and rerun; the preflight reads session lifetimes before a run.empty --runtime gcloud-east1needs the AWS session for the same reason.- verification failed on
booted imagewith a launch record ofunbound. The instance's image was baked in the same run, so nothing was pinned; the instance is left standing by the rule. Verification requires the booted image to be a recorded build of the instance's image series on its runtime, so it never compares against the literalunbound; the next instance-image run resumes the sequence. gce-verifynever sawstartup-script exit status 0. Newer guest agents logFinished running startup scriptsinstead, and the hook accepts both lines. A verification that reportsno completion on the serial console within <timeout>son a healthy instance means a third spelling: readserial_consoleoutput (theevidenceinverifications.yaml) and extend the pattern.- a dask bake timed out waiting for SSH through the IAP tunnel. Either the IAP lookup lag above or a download stall (GitHub's release downloads returning 504). The retry boots, provisions in about 90 s and images cleanly.
- every bake timed out
waiting for SSH. IAP runtimes bake through the tunnel (use_iap = true), not over the build VM's external IP on tcp:22, so a bake does not depend on the default VPC'sdefault-allow-sshrule (deleting that rule is deliberate hygiene). The operator prerequisite isroles/iap.tunnelResourceAccessorfor the runner service account; the symptom means that role is missing. - the instance boot disk is 200 GB, about $8/month. The boot disk
inherits the image's
disk_size, which inherits the OS builder's 200 GB default (a RHEL vendor minimum carried forward) when nothing narrower is declared.default_disk_sizeon the runtime wins; the fixture bakes at the vendor image's 10 GB floor (a boot disk cannot be smaller than its source image). - every SSH/IAP session to the launched instance refused. At first
boot the guest agent removes users absent from metadata; when the bake
user's
google-sudoersmembership is missing (the agents race over it during bakes)gpasswdexits 3 and the agent aborts its whole metadata-ssh-key setup, so no operator key is ever provisioned.bake_finalize_commandsguarantees the membership as the bake's last act. The symptom means the finalize provisioner is not the last one in the emitted-build.pkr.hcl(the testtest_gce_bakes_end_with_the_finalize_provisionerguards it). - ansible tasks die
unreachable / Failed to create temporary directory. Packer's ansible provisioner defaultsansible_userto the operator's local login, not the build VM's ssh user, so ansible builds~/.ansible/tmpunder/home/<local-user>; intermittent because packer'suse_proxyauto-detection masks it.bake_ssh_username(image)pins the provisioneruserto the bake's user, the one the packer source resolves, so the symptom means the emitted provisioner'suserand the source'sssh_usernamedisagree. - the base bake used ssh user
ec2-userwhile the instance bake fell back topacker. The new-generation guest agent removes the other-name user at first boot and aborts key provisioning; one GCE chain must bake every image as ONE user. Declaressh_usernameon the OS-builder runtime entry (it covers the chain), or on the runtime.validaterefuses a chain whose images would bake as different users, and the GCE family default ispacker. - a dask bake fell through to the runtime's 1 GB machine and OOMed.
The packer source's
machine_typefollows the AWS-parity chain: the OS-builder runtime entry'smachine_type, itsdefault_machine_type, then the runtime'sdefault_machine_type. A bake that needs memory declares it on the entry; the runtime default is the free-tiere2-microin the fixture. - underscores in GCE names. GCE refuses
_in resource and device names; every name goes throughgce_name(). A data disk attached under its sanitised name must be mounted by that same name (/dev/disk/by-id/google-gce-data): one sanitisation serves both sides.
Failures the code raises, by where they surface:
- Load.
No usable GCP project could be resolved for cloud builder <name> (no `project_id` declared on the runtime). Skipping network validation; image resolution and build execution will not work until valid GCP credentials are configured.(WARNING): noproject_id; add one.No networking configuration provided for GCP cloud builder <name>(WARNING): bakes and instances will carry nosubnetwork.No network specified ... and no 'default' network found in GCP project,Network <n> ... not found in GCP project,Subnetwork <id> ... not found in network <n>(ERROR, then aValueErrorthat ends the load, exit 1): fix the declaration or the project.GCP Error: <api error>(ValueError): the API refused the listing, usually permissions or a disabled Compute API. An auth error (DefaultCredentialsError, no ADC) is not wrapped and ends the load with the library's own message: run the ADC login above.Network tag <t> ... is not targeted by any firewall rule(WARNING): the tag selects nothing. validate/ generation.GCP runtime <name>: unknown session mechanism '<x>' (supported: iap)(ValueError): onlyiapexists.gcloud: binary '/usr/local/bin/gcloud' not found,gcloud: GCPCLIVersionChecker could not parse a version from ...,gcloud <v> does not meet its requirement >=500 (cfg/executables.yml): install or upgrade the SDK, or move the floor inexecutables.yml.Executable gcloud specified for provider <runtime> not found in executables list.: the runtime'sexecutable(defaultgcloud) names no declared entry; declare- name: gcloudwith itsbinary, or pointexecutableat the entry you have. The same cause at a session or lookup readsGCP runtime <name>: executable 'gcloud' is not declared in cfg/executables.yml.<image|instance|storage> '<name>': tag key '<key>' on runtime <rt>: GCE label keys must start with a lowercase letter; '<key>' becomes '<label>'; rename the key(fromvalidate, exit 1): a tag key declared on that image, instance or storage would become a label key GCE refuses (a key such as2024). Rename the key in the YAML; nothing renames it for you.- A session command (post-bake verify, unmount, the alias writer).
GCP runtime <name> declares no session_mechanism, so no session command can reach its instances (supported: iap): declaresession_mechanism: iap(and its firewall rule and grant) or run nothing that needs a session on that runtime. - Resolution (
resolve, the base-image phase of a run).Owner 'self' requires a project in the session configuration (set project_id on the runtime builder ...);No usable GCP projects resolved from query ...(every owner was dropped as invalid);Failed to query images in project '<p>' with filter: <error>andFailed to query image family '<f>' in project '<p>': <error>(ImageQueryError: permissions or an unknown project);No resolved Image identifiers for OS <name> in predefined_resolve(the base's message when the query matched nothing: loosenfilters, check the owner and thestatus);OS builder <name>: image_id '<id>' on runtime <rt> is not known to the provider(the pinnedimage_idnames no image in the entry's owner projects; check the name and that its project is among the owners);Could not get owning project for image <name>(a result with neitherprojectnor aself_link; not expected from the API). Each ends the run, exit 1. - The state query.
state query images/<rt> unavailable: GCP runtime <rt>: no project to queryor an API error: anunavailable:line, never drift;state query --strictstill refuses on a session that will not outlast the run, and a plain run warns.instances/<name>: booted image (runtime <rt> could not answer): the boot probe returnedNoneand the machine is not stopped; the DEBUG log carries the exception. - Verification.
verify <name>: startup scripts: FAILED -- an explicit failure line(astartup-script exit status <non-zero>or afailed/errorstartup line on the console; read theevidence);no completion on the serial console within <t>s(the agent never reported; raise--timeout, read the console);booted image: FAILED -- booted <x>, expected <y>(the instance did not boot its pin:upgrade instanceand replace, orstate queryto see the mismatch);booted <x>, which lineage does not record for <image> on <rt>;data disks mounted: FAILED -- <n> clean XFS mount(s) on the console, <m> declared(the startup script did not format or mount a pd: the device name and the by-id path must agree);declared tests: FAILED -- k of n failed: ...(the image's post-bake suite; the per-build record inimage-tests.yamlnames the assertion;releaserefuses the build).GCP runtime <rt>: no project/zone to read a serial console(RuntimeError): declarezone. AVerificationFailedleaves the instance standing underkeepand fails the run. - Session commands. A non-zero exit from
gcloud compute sshis returned with the combined output:unmount storagewrites a failed receipt and raisesunmount of <mount> on <instance> failed (exit <rc>), the alias writer logsalias write failed (<rc>): <tail>,wait_until_reachablekeeps polling until its deadline, and a post-bake suite shows asno result. The usual causes are the missing IAP role or firewall rule, a passphrase-protected key, or a machine still booting.GCP runtime <rt>: no project/zone for a session command: declarezone. - Power state.
GCE runtime <rt>: instance '<n>' reports unrecognised status '<s>'; treating it as unknown(WARNING): a status outside the eight the map knows; nothing acts on it.GCP runtime <rt>: no project/zone to start an instance/... to stop an instance(RuntimeError).<n>: FAILED to stop it again after <why>: <error>. It was switched off before this run and is now RUNNING -- stop it by hand.(ERROR fromrunning_for_task): the one case that leaves a billable change behind; stop the instance. empty --runtime.GCP runtime <rt>: no project/zone to inventory;gcloud storage buckets list: <stderr tail>(the gcloud account cannot list buckets, or is not logged in): exit 2. A leftover named underleftoversis exit 1: dispose or decommission it through the recorded path, never by hand.- Retention and
dispose image.GCE image <id> not found in <p>; nothing to delete(WARNING,deleted=False): the image was already gone; the record is dropped anyway.GCP runtime <rt>: no project to dispose in(RuntimeError). An API error (permissions, an image in use by a disk) propagates and stops the retention step; the record then still exists and the next run retries. - Relabel.
relabel: could not retag <id>: <error>(WARNING,retagged=False): the record is right and the state query keeps showing the tag.relabel: <id> is not in <rt>; nothing to relabel: the image is gone; the state query reports itmissing. The post-bake retag has no guard: an error there fails the bake's record step. - Names.
gce_name()never fails; two csis names that differ only in characters it strips (a_banda-b, or case) collide on GCE, and the second bake or launch fails with the API'salready exists. Keep names distinct in the lowercase[a-z0-9-]alphabet.
Related
- aws-runtime-plugin: the other runtime type, with the same hook surface on EC2.
- default-os-plugin: the OS builders whose runtime entries this plugin resolves to GCE images.
- tf-gcp-plugin: the GCE instance and storage roots that read this model.
- dummy-plugin: the extension template.
- Base classes: runtime.py, cloud_builder.py, credentials.py, provider_specific_image.py, builder_base_runtime.py, abstract_version_checker.py, power_state.py.
- Consumers of the hooks: state_query.py, retention.py, dispose.py, verify_instance.py, runtime_facts.py, relabel.py, provider_aliases.py, generations.py, validate.py.
- docs/OPERATIONS.md for the credential contract and the operator's cycles; docs/DESIGN.md for the design; docs/PLUGINS.md for the package index.
- The configuration reference -- every field of the YAML this plugin reads, with an example.
Metadata
Release files for cs-image-system-gcloud-runtime-plugin 0.1.7
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cs_image_system_gcloud_runtime_plugin-0.1.7.tar.gz | 94.9 kB | Without provenance | Details for cs_image_system_gcloud_runtime_plugin-0.1.7.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cs_image_system_gcloud_runtime_plugin-0.1.7-py3-none-any.whl | Python 3 | none | any | Details for cs_image_system_gcloud_runtime_plugin-0.1.7-py3-none-any.whl |
Total release size: 175.6 kB
Release files / cs_image_system_gcloud_runtime_plugin-0.1.7.tar.gz
| Download URL | cs_image_system_gcloud_runtime_plugin-0.1.7.tar.gz |
|---|---|
| Size | 94.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9e037c0db13280f927fd7ee1c0b3517ea6391bbe5022ca002adfa9a9bc80bafb
|
|
BLAKE2b-256 checksum How to use checksums |
4dc2443b63159bf8fc1f3b28f1b3b6bb2940b910cdfd5c1ec726512d9f6a9edd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.18 {"installer":{"name":"uv","version":"0.12.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / cs_image_system_gcloud_runtime_plugin-0.1.7-py3-none-any.whl
| Download URL | cs_image_system_gcloud_runtime_plugin-0.1.7-py3-none-any.whl |
|---|---|
| Size | 80.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2962fff8d6df2305487a4da7687d767c2762edd67c80406473c373ebc2501dea
|
|
BLAKE2b-256 checksum How to use checksums |
c6bd34021981e7d6b7b9254015abd6cfc8627b0a31b2ce3f8a58f4703c20c8a2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.18 {"installer":{"name":"uv","version":"0.12.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for cs-image-system-gcloud-runtime-plugin 0.1.7
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.