Skip to content

About

CLI tool for managing GCP Hosted Control Planes

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

gcp-hcp-ctl

CLI for managing GCP Hosted Control Plane (HCP) clusters.

Part of the GCP HCP project. See design decisions for architectural context.

Quick Start

# Build
make build

# Configure (project and region are required)
mkdir -p ~/.gcphcpctl
cat > ~/.gcphcpctl/config.yaml << EOF
project: your-gcp-project-id
region: us-central1
EOF

# Or use flags / env vars instead
export GCPHCPCTL_PROJECT=your-gcp-project-id
export GCPHCPCTL_REGION=us-central1

Commands

Cluster Lifecycle (cluster)

Create, inspect, list, delete, and log in to clusters via the platform API server.

# Step 1: Create network and IAM resources (customize as needed)
gcphcpctl network create my-infra-id --project my-project --output-file network-output.json
gcphcpctl iam create my-infra-id --version 5.1.0-ec.3 \
  --project my-project --output-file receipt.json

# Step 2: Create a cluster using pre-created IAM and network configs
# receipt.json must be a complete receipt from 'gcphcpctl iam create --version'
# (see the IAM section); cluster create refuses partial, blocked or legacy files
gcphcpctl cluster create my-cluster \
  --iam-config-file receipt.json \
  --network-config-file network-output.json \
  --version 5.1.0-ec.3 --channel-group candidate

# Enable the cluster Ingress capability (*.apps DNS, default wildcard certificate)
# --enable-ingress is what opts in; the receipt always includes the ingress-op
# service account, but the payload only wires it with the flag
gcphcpctl cluster create my-cluster \
  --iam-config-file receipt.json \
  --network-config-file network-output.json \
  --version 5.1.0-ec.3 --channel-group candidate --enable-ingress

# Dry run (show payload without creating)
gcphcpctl cluster create my-cluster \
  --iam-config-file receipt.json \
  --network-config-file network-output.json \
  --version 5.1.0-ec.3 --dry-run

# Get a cluster by name or ID
gcphcpctl cluster get my-cluster
gcphcpctl cluster get my-cluster -o json

# List all clusters
gcphcpctl cluster list
gcphcpctl cluster list -o json

# Delete a cluster (requires confirmation)
gcphcpctl cluster delete my-cluster --confirm

# Log in to a cluster (configures kubeconfig with gcloud exec auth)
gcphcpctl cluster login my-cluster

# Log in with a custom kubeconfig path
gcphcpctl cluster login my-cluster --kubeconfig ~/.kube/config

Cluster commands use the platform API endpoint discovered from --region and --env (or their environment variables or config keys). To override the API endpoint, set --api-endpoint (hidden from help), GCPHCPCTL_API_ENDPOINT, or the api_endpoint config key.

Manual control-plane upgrades

Request a minor stream or an exact release through the existing Cluster. Version strings must not contain whitespace, a leading v, or build metadata:

# Let the server select the newest eligible patch in the requested minor
gcphcpctl cluster upgrade control-plane my-cluster --version 5.0

# Request an exact eligible release
gcphcpctl cluster upgrade control-plane my-cluster --version 5.0.9

# Inspect the running version, target, and upgrade conditions
gcphcpctl cluster get my-cluster

The command patches only spec.release.version, preserving channel and maintenance settings. The server validates the upgrade path and approves the rollout when its checks permit it. Saving the desired release does not mean rollout has started. cluster get shows the observed Current Version and desired Target Version separately, including while an upgrade is pending or being applied. The upgrade command also supports -o json and -o yaml to return the updated Cluster. Text lists add a TARGET VERSION column when any listed cluster has a pending target; the VERSION column continues to show the observed release.

Nodepool Management (nodepool)

Create, inspect, list, scale, upgrade, and delete nodepools via the platform API server.

# Create a nodepool in a cluster
gcphcpctl nodepool create my-nodepool --cluster my-cluster \
  --zone us-central1-a --subnet my-subnet --version 5.0.0 --replicas 2
gcphcpctl nodepool create workers --cluster my-cluster \
  --zone us-central1-a --subnet my-subnet --version 5.0.0 \
  --replicas 3 --instance-type n2-standard-8 --disk-size 200
gcphcpctl nodepool create workers --cluster my-cluster \
  --zone us-central1-a --subnet my-subnet \
  --replicas 2 --version 5.1.0-ec.3 --channel-group candidate

# Get a nodepool by name or ID
gcphcpctl nodepool get my-nodepool
gcphcpctl nodepool get my-nodepool -o json

# List all nodepools (or filter by cluster)
gcphcpctl nodepool list
gcphcpctl nodepool list --cluster my-cluster
gcphcpctl nodepool list -o json

# Scale a nodepool
gcphcpctl nodepool scale my-nodepool --replicas 5

# Request an upgrade (preserves an existing schedule; immediate if none exists)
gcphcpctl nodepool upgrade my-nodepool --version 5.0.0

# Schedule the earliest upgrade start (RFC 3339)
gcphcpctl nodepool upgrade my-nodepool --version 5.0.0 \
  --start-time 2026-11-20T03:00:00Z

# Explicitly clear a pending schedule to make the upgrade immediately eligible
gcphcpctl nodepool upgrade my-nodepool --version 5.0.0 --clear-start-time

# Inspect upgrade progress and conditions on the NodePool
gcphcpctl nodepool get my-nodepool

# Delete a nodepool (requires confirmation)
gcphcpctl nodepool delete my-nodepool --confirm

Upgrades update spec.release.version and optional spec.release.upgradeStartTime on the existing NodePool. Targets require a full version, including the patch and any prerelease suffix (for example, 5.1.0-ec.2). The server validates eligibility and rejects release changes while an upgrade is in progress. Repeating identical settings is idempotent. --start-time is the earliest permitted start, not a promise of an exact start time. Omitting --start-time preserves the existing schedule. --clear-start-time explicitly sends upgradeStartTime: null to remove it; this flag cannot be combined with --start-time. Start times must use whole seconds; fractional timestamps are rejected.

nodepool get shows the observed status.version as Current Version and the desired release as Target Version. Lists show the observed VERSION and a separate TARGET VERSION while an upgrade is pending or progressing. Upgrade conditions appear in nodepool get; -o json and -o yaml return the NodePool resource.

Nodepool commands use the same endpoint discovery as cluster commands, and the same GCPHCPCTL_API_ENDPOINT / api_endpoint escape hatch to bypass it.

Platform API errors and troubleshooting

Cluster and nodepool commands add operation or resource context to a fixed, safe error label. For example, command stderr can contain:

Error: listing clusters: not authenticated
Error: listing clusters: permission denied
Error: looking up cluster "missing" in project "my-project": not found
Error: creating nodepool: service unavailable; check the resource before retrying

not authenticated means the request did not have accepted authentication. permission denied is a generic access-denied label, not a diagnosis of a missing role, binding, or policy rule. Check the selected project and configured identity source; if access is expected, contact an administrator. ESPv2 may reject a request before it reaches the Platform API, and not every 401 response has a representation the CLI can interpret.

Other validation, conflict, not-found, and service errors also use fixed labels. Normal errors omit HTTP codes, the words Platform API, and free-form server message, details, and causes, including any tokens, authorization headers, claims, or credential-bearing URLs in those fields. The typed platformapi.HTTPError retains HTTP status and request metadata for callers and tests. Unsupported response content types, token acquisition failures, and network failures may instead display request failed; a timeout can display request timed out. When the gcloud fallback cannot obtain an identity token, the CLI instead reports not authenticated; run gcloud auth login. -o json changes successful result output, not this error contract. Failed commands exit non-zero.

If a create fails and its outcome is uncertain, inspect the resource before retrying.

API tracing and verbosity

Use kubectl-style numeric verbosity (--v=N or -v=N) for progressively more HTTP detail on stderr while normal command output stays on stdout:

gcphcpctl cluster list --v=6
# Include the serialized JSON POST payload and successful response body:
gcphcpctl rolebinding create test-rb --subject=user@example.com --platform-role=cluster-admin -v=8
gcphcpctl nodepool list -v=6 -o json >nodepools.json 2>api-trace.log
GCPHCPCTL_VERBOSITY=6 gcphcpctl cluster list
gcphcpctl cluster list --v=0

The default is 0. You can also set verbosity: 6 in the config file. Flags override GCPHCPCTL_VERBOSITY, which overrides the config file; explicit 0 at a higher priority disables tracing. Levels must be nonnegative integers. -v6 and -v 6 also work; bare -v requires a value. The standalone gcphcpctl-ops binary supports the same flag and setting.

  • Levels 0–5: no additional HTTP tracing.
  • Level 6: method, sanitized URL, response status, and elapsed time.
  • Level 7: also request headers, with credential-bearing and unknown header values redacted.
  • Level 8: also response headers and supported request/response JSON bodies, truncated to 1,024 bytes after redaction.
  • Level 9: also a redacted curl representation and DNS/connect/TLS/first-byte timing details; the body output limit increases to 10,240 bytes.
  • Level 10 and above: the same details with no JSON body output truncation.

These HTTP detail thresholds and output limits follow client-go. Tracing remains invocation-scoped rather than enabling global klog output; credentials are never intentionally unmasked at higher levels. The curl representation excludes the body, which is logged separately, and is not a credential-complete replay command.

Each HTTP attempt gets a timestamped start line containing a request ID, method, and sanitized URL, followed by a matching completion line with numeric status and elapsed time. Application-level retries and redirects produce separate pairs; internal connection retries within Go's HTTP transport are not separately traced. Timing ends when response headers arrive, not when a streaming body finishes. At level 9+, connect sums completed connection attempts (including failed and overlapping attempts), so it can exceed elapsed wall time. first_byte measures from base-transport timing start to the first response byte, including a possible 100 Continue response; it is not measured from upload completion. A timing with no observed callback is shown as zero. Failed transport attempts use fixed error labels, not raw error prose; a failure before token acquisition completes produces no API request trace.

Body logging is limited to complete JSON (application/json and supported +json content types). Credential-like fields, Kubernetes Secret data, and recognized embedded credential strings/URLs are redacted before truncation. Request logging uses a replayable body snapshot and never consumes the body sent to the server. Response logging observes only bytes the caller reads, emitting a body entry at EOF or after a complete known-length read followed by Close; it never pre-reads or drains a response.

Explicit omission markers explain non-replayable requests, incomplete/malformed JSON, encoded or unsupported bodies, SSE/NDJSON/watch streams, and non-success response bodies. Error response bodies remain omitted to preserve the CLI's safe error-normalization contract. At levels 8 and 9, JSON capture is limited to 16 MiB; larger bodies are omitted rather than redacting an incomplete prefix. Level 10 removes this capture limit too and can consume substantial memory for large JSON responses. Recognized streams are not captured, and no response is forced to completion.

Authorization, cookies, API keys, and unknown header values are masked. URL hostnames/IP addresses and ports are replaced with REDACTED in request traces, curl diagnostics, and URLs embedded in headers or JSON bodies. Request destinations are unchanged. URL userinfo/fragments are omitted, workflow callback identifiers are redacted, and query values are redacted by default except narrowly validated metadata values. Redaction cannot identify every sensitive value in arbitrary application data: resource names, subjects/emails, and ordinary body fields remain visible. Treat high-verbosity logs as sensitive operational data and review them before sharing. Verbosity does not change normal command output, error labels, or exit status.

Coverage is intentionally limited to the Platform API, endpoint discovery, Cloud Run diagnose/chat HTTP calls, direct Workflows REST calls (callbacks and PAM-tag checks), and the companion's PagerDuty HTTP calls. It does not trace Google SDK REST/gRPC clients (including Workflows execution/management, PAM, IAM, networking, and audit logging), credential/token exchanges, calls inside gcloud subprocesses, or API calls made remotely by Cloud Workflows or agents. An untraced command may therefore make API calls without producing trace lines.

IAM Infrastructure for Hosted Clusters (iam)

Create and destroy Workload Identity Federation (WIF) infrastructure for HyperShift clusters, including WIF pools, OIDC providers, and Google Service Accounts with IAM role bindings.

The full customer-facing lifecycle — iam create → cluster create --iam-config-file → iam verify → iam update → cluster delete → iam destroy, with the receipt handover, drift classes and remediation, exit codes and the teardown ordering rationale — is documented in docs/iam-lifecycle.md. To discover what exists before creating anything: versions get <version> shows a release's IAM contract and wifconfigtemplate list/get browse the contract catalog.

iam create and network create verify up front that the Google Cloud services they depend on are enabled in the target project, and fail fast with the gcloud services enable command to run otherwise. Every checked service is one whose disablement demonstrably breaks the platform:

  • iamcredentials.googleapis.com — not called by the CLI itself, but by the hosted control plane, which exchanges workload identity tokens for service-account credentials; without it node pools cannot create GCE instances
  • compute.googleapis.com — VPC, subnets, firewall, node instances
  • dns.googleapis.com — the control plane creates a private Cloud DNS zone for the cluster domain; without it workers cannot resolve the ignition endpoint and never join
  • networkservices.googleapis.com — ingress components
  • networkmanagement.googleapis.com — connectivity checks

The corresponding onboarding command is:

gcloud services enable iamcredentials.googleapis.com compute.googleapis.com \
  dns.googleapis.com networkservices.googleapis.com \
  networkmanagement.googleapis.com --project=$PROJECT_ID

The check itself needs serviceusage.googleapis.com and roles/serviceusage.serviceUsageViewer. iam.googleapis.com and cloudresourcemanager.googleapis.com are deliberately not checked: both function regardless of their Service Usage state (service-account creation and project lookups succeed while both report disabled), so their state carries no signal about whether the platform will work.

# Create IAM infrastructure for a cluster from the release's catalog contract
gcphcpctl iam create <infra-id> --version 5.1.0-ec.3 \
  --oidc-issuer-url https://oidc.example.com/my-cluster
gcphcpctl iam create <infra-id> --version 5.1.0-ec.3 \
  --oidc-issuer-url https://oidc.example.com --output-file receipt.json

# Or derive a compliant infra ID from the cluster name (printed and recorded
# in the receipt; re-use it verbatim to re-run or destroy)
gcphcpctl iam create --cluster-name my-cluster --version 5.1.0-ec.3 \
  --oidc-issuer-url https://oidc.example.com --output-file receipt.json

# Verify a cluster's installation IAM against its pinned catalog contract
gcphcpctl iam verify <cluster-name>

# Apply one more contract application to a cluster's installation IAM
gcphcpctl iam update <cluster-name> --version 5.1.0-ec.4

# Destroy IAM infrastructure for a cluster
gcphcpctl iam destroy <infra-id>
gcphcpctl iam destroy <infra-id> --yes    # skip confirmation prompt

iam verify is read-only and takes the cluster as the authority: the Cluster's spec.platform.gcp.iam pins the applied contracts, and every planner input (project, infra ID, worker service account, OIDC issuer) comes from the Cluster spec. The pinned contracts are re-fetched from the catalog and re-verified, the expectation is re-rendered as the union across all pinned applications (matching additive retention), and actual cloud state is diffed against it: custom-role permissions, component service accounts, the WIF pool and provider, project bindings, WIF bindings, worker actAs grants and the cluster's own workload-identity wiring. Exit codes: 0 in sync, 1 drift found, 2 error. Without a cluster there is nothing to verify — iam create converges missing resources.

iam update applies one more contract application, additively. The release's contract is resolved from the catalog, the installation is verified first — the update refuses to run over diverged, tombstoned or mis-wired state (exit code 1, with the verification report) — and the union of every pinned application plus the new one is converged onto the project: missing resources are created, an earlier application's custom-role permissions are grown to the union, grants are added, nothing is ever removed. The cloud converges fully before the new application is appended to the Cluster's pin list, so the CR never describes a half-applied state; the append is guarded against concurrent changes to the pin list. The drift gate verifies against the pins plus the release being applied, so an update whose pin append failed mid-flight can simply be re-run: the already-converged state passes the gate. Applying a contract the cluster already pins is a no-op. Exit codes: 0 applied or already applied, 1 drift refused the update, 2 error.

--version resolves the release's WIFConfigTemplate IAM contract from the catalog, renders the exact installation resources (custom roles, component service accounts, WIF pool and provider, grants) and preflights them against the project: collisions with foreign resources, soft-deleted tombstones, permissions that cannot be granted in custom roles, a missing default Compute worker service account or exceeded custom-role quota all stop the run before anything is created.

Permissions GCP reports as TESTING custom-role support do not block the run: the published catalog contract is the policy that justifies using them, and GCP accepts them in custom roles. They are recorded as preflight warnings in the preview output and carried on the receipt, so a complete receipt durably shows which granted permissions rely on Google's testing surface.

The run converges: existing resources with exactly the planned content are adopted, absent ones are created, and re-running after a partial failure completes the remainder. A receipt is written on every exit path once the contract is resolved and the plan is rendered (stdout by default, --output-file to keep it) with a status of complete, partial or blocked; earlier failures — authentication, discovery, catalog resolution — exit without a receipt, as nothing has been decided about the project yet.

cluster create --iam-config-file only accepts a complete receipt: partial, blocked, pre-catalog legacy files and receipts missing their contract pinning are refused with a re-run hint (the create run converges onto existing resources). The receipt's contract assertion is wired into the cluster as spec.platform.gcp.iam (the pinned WIFConfigTemplate application and the default Compute worker service account), which becomes the durable authority once the cluster is created — the receipt file is only the handover artifact.

All create operations are idempotent (safe to run multiple times). Destroy operations tolerate not-found errors gracefully.

The catalog contract grants the control-plane component the permissions it needs to manage the worker firewall rule. Re-run gcphcpctl iam create <infra-id> --version <version> on clusters created before that grant existed to apply it (the run converges onto existing resources).

Optional Ingress service account

The cluster Ingress capability is opt-in. With the catalog-driven iam create, the ingress-op service account is contract-required: every receipt reports its email in serviceAccounts.ingress-op:

{
  "serviceAccounts": {
    "ctrlplane-op": "<infra-id>-ctrlplane-op@<project>.iam.gserviceaccount.com",
    "ingress-op": "<infra-id>-ingress-op@<project>.iam.gserviceaccount.com"
  }
}

cluster create sets spec.platform.gcp.workloadIdentity.serviceAccountsRef.ingressEmail only when --enable-ingress is passed, and that field is what enables Ingress: the guest ingress operator publishes the *.apps Cloud DNS records and the platform stages the default wildcard certificate via ACME DNS-01 delegation.

--enable-ingress is the capability signal. The ingress-op account is created unconditionally on every installation (the contract requires all components), so its presence in the receipt means nothing by itself: without the flag the payload omits ingressEmail and Ingress stays disabled. ingressEmail is immutable, so Ingress cannot be enabled after cluster creation — pass --enable-ingress at create time if you may want it; the infrastructure cost is nil either way.

iam destroy is catalog-aware in its naming: the installation's resources carry the contract-rendered names (the ingress-op entry matches openshift/hypershift#9958 exactly), so the optional ingress account is cleaned up whether or not it was created; missing resources are tolerated.

iam destroy is CR-less by design: the control plane needs this IAM to tear down its own resources, so the documented flow is cluster-delete first, iam destroy last — by which time the Cluster (and its CR) is always gone. The installation is discovered from the infra ID alone as the namespace closure: its custom roles, component service accounts, workload identity pools and providers, the project bindings on its roles, and its members on the shared worker service account. Matching is boundary-aware, so an installation whose infra ID is a prefix of another's never matches the other's resources. The found set is shown in full and must be confirmed before anything is removed. Removal is convergent (re-running completes the remainder) and ordered: project bindings, this installation's members on the shared worker account, the component accounts, the providers, the pools, and the custom roles last. The shared worker service account itself is never deleted — sibling installations in the same project keep their grants. Exit codes: 0 destroyed (or nothing to destroy), 1 aborted at the confirmation, 2 error.

Network Infrastructure for Hosted Clusters (network)

Create and destroy GCP network infrastructure including VPC networks, subnets, Cloud Routers, and Cloud NAT.

# Create network infrastructure for a cluster
gcphcpctl network create <infra-id>
gcphcpctl network create <infra-id> --vpc-cidr 10.1.0.0/24
gcphcpctl network create <infra-id> --output-file network-output.json

# Destroy network infrastructure for a cluster
gcphcpctl network destroy <infra-id>
gcphcpctl network destroy <infra-id> --yes    # skip confirmation prompt

All create operations are idempotent (safe to run multiple times). Destroy operations delete resources in reverse dependency order and tolerate not-found errors gracefully.

Worker firewall rule ownership

The control-plane-operator (CPO) owns and creates the worker firewall rule <infra-id>-internal-cluster for supported payloads. Private Preview supports OpenShift 5.0.0 GA and later only; pre-GA candidates such as 5.0.0-ec.* are not supported and may lack the CPO firewall backport. This CLI never creates the rule, and network destroy does not delete it; delete any remaining <infra-id>-internal-cluster or legacy <infra-id>-allow-kubelet rule manually before destroying the VPC.

Prerequisites and teardown

  • CPO needs roles/compute.securityAdmin to manage the rule. gcphcpctl iam create grants it, but existing clusters created before this role was added must re-run gcphcpctl iam create <infra-id> --version <version>; otherwise the GCPFirewallRulesReady condition reports a permission failure indefinitely.
  • Delete the HostedCluster before network destroy so CPO tears down its rule, then delete any remaining <infra-id>-internal-cluster or legacy <infra-id>-allow-kubelet rule manually. This CLI does not delete firewall rules, and GCP refuses to delete a network that a firewall rule still references. Removing the rule while CPO is still reconciling can leave the HostedCluster degraded.

Dry-run previews

Add --dry-run to network create, iam create, or nodepool create to preview the intended resources without provisioning them:

gcphcpctl network create preview-test --project PROJECT_ID --region us-east1 --dry-run
gcphcpctl iam create preview-test --project PROJECT_ID --region us-east1 \
  --version 5.0.2 --dry-run
gcphcpctl nodepool create workers --project PROJECT_ID --region us-east1 \
  --cluster my-cluster --zone us-east1-b --subnet my-subnet \
  --version 5.0.0 --replicas 2 --dry-run

Network previews show planned resource names using the same naming rules as real creation. They do not construct Google Cloud clients or write --output-file.

IAM dry runs resolve the release's catalog contract and run the same read-only planning and preflight checks as normal creation. They require Platform API and Google Cloud read access, and report existing resources, required APIs, custom-role quota, and permission support. The command prints the plan and exits before creating resources or writing a receipt; --output-file is untouched. Blocking findings are printed and cause a non-zero exit. Use --output json or --output yaml for a structured preview. With --cluster-name, the preview generates an infra ID; pass that ID explicitly to creation to use the same names.

Node-pool dry runs print the request without resolving platform endpoints, loading credentials, or constructing an API client. Default text output includes a banner and JSON; --output json or --output yaml emits only the resource so it can be parsed or redirected to a file. Existing local input and configuration validation still applies.

The existing cluster create --dry-run is unchanged and still needs IAM/network config files and the existing endpoint/version lookups. That preview is not a live readiness or server-admission check.

Network and node-pool previews do not verify billing, enabled APIs, quotas, permissions, existing resource names, or actual capacity. Normal creation retains its existing API checks and authentication requirements.

Operational Debugging (ops)

Convenience wrappers that run Cloud Workflows to interact with GKE clusters without direct cluster access (Zero Operator Access).

# Get resources (kubectl-style)
gcphcpctl ops get pods -n hypershift
gcphcpctl ops get nodes
gcphcpctl ops get deployments -n kube-system
gcphcpctl ops get hc -n clusters               # aliases: hc, hcp, np, deploy, svc, etc.

# Get raw JSON response (full Kubernetes API output)
gcphcpctl ops get pods -n hypershift -o json

# AI-powered pod analysis (uses Vertex AI to diagnose issues from logs/events)
gcphcpctl ops get pods my-pod -n hypershift --analyze

# Pod logs
gcphcpctl ops logs my-pod -n hypershift
gcphcpctl ops logs my-pod -n hypershift -c etcd --tail 50

# Describe resources
gcphcpctl ops describe pods my-pod -n hypershift
gcphcpctl ops describe deployment my-deploy -n kube-system

# Delete resources (pods, jobs, deployments)
gcphcpctl ops delete pods my-pod -n clusters-abc123
gcphcpctl ops delete pods my-pod -n clusters-abc123 --grace-period 0

# Expand PVC storage
gcphcpctl ops expand-volume data-etcd-0 -n clusters-abc123 --size 20Gi

# etcd operations
gcphcpctl ops etcd health -n clusters-abc123
gcphcpctl ops etcd status -n clusters-abc123
gcphcpctl ops etcd member-list -n clusters-abc123
gcphcpctl ops etcd defrag -n clusters-abc123

Workflow Management (ops wf)

Direct Cloud Workflow management for arbitrary workflow execution.

# List deployed workflows
gcphcpctl ops wf list

# List execution history for a workflow
gcphcpctl ops wf list get --limit 5

# Run a workflow
gcphcpctl ops wf run get --data '{"resource_type": "pods", "namespace": "hypershift"}'

# Run async (returns immediately)
gcphcpctl ops wf run describe --data '{"resource_type": "pods", "name": "etcd-0"}' --async

# Check execution status
gcphcpctl ops wf status get <execution-id>

# Resume a paused workflow (callback)
gcphcpctl ops wf resume approval-flow <execution-id> --data '{"approved": true}'

Configuration

Configuration priority: CLI flags > environment variables > config file.

For cluster and nodepool commands, set a public GCP region and environment to discover the platform API endpoint. cluster create also discovers the OIDC issuer. Explicit endpoint values take precedence over discovery, including values in the config file.

gcphcpctl regions list --env integration
gcphcpctl cluster list --region us-central1 --env integration
gcphcpctl cluster create my-cluster --region us-central1 --env integration \
  --iam-config-file receipt.json --network-config-file network-output.json \
  --version 5.0.0 --project my-project
Flag Env Var Config Key Description
--project GCPHCPCTL_PROJECT project GCP project ID
--region GCPHCPCTL_REGION region GCP region
--environment / --env (hidden) GCPHCPCTL_ENVIRONMENT environment / env Environment for endpoint discovery; not shown in help (default: production)
--output / -o - output Output format: text, json, yaml
--v=N / -v=N GCPHCPCTL_VERBOSITY verbosity Nonnegative integer, default 0; HTTP metadata at 6, headers at 7, JSON bodies at 8, curl/timing at 9, untruncated JSON at 10
--api-endpoint (hidden) GCPHCPCTL_API_ENDPOINT api_endpoint Explicit platform API endpoint; overrides discovery; not shown in help
--oidc-endpoint (hidden) GCPHCPCTL_OIDC_ENDPOINT oidc_endpoint Explicit OIDC issuer base URL; overrides discovery; not shown in help

Config file location: ~/.gcphcpctl/config.yaml

Endpoint discovery

--env selects the environment for endpoint discovery. Commands that target a region also use --region. When no environment is selected by flag, environment variable, or config, the CLI uses production. --env accepts a known environment name (integration, stage, production) that maps to a discovery subdomain, or — for a shared dev sector or an ephemeral CI run — the discovery subdomain itself, e.g.:

gcphcpctl regions list --env integration
gcphcpctl regions list --env <infra-id>.dev

Discovered endpoints must be HTTPS under gcp-hcp.devshift.net. role and rolebinding commands use the environment's global authorization endpoint, so they do not need --region when that endpoint is available. In environments still using regional discovery, they require --region to select a Platform API endpoint.

Precedence: explicit endpoint flags (hidden from help), environment variables, and config values win over discovery, in that order. Regional commands skip discovery when both --api-endpoint and --oidc-endpoint are explicit; role and rolebinding commands skip it with an explicit --api-endpoint. In either case, neither --env nor --region is required. For an environment without a discovery manifest, supply the endpoints explicitly.

Project Structure

cmd/gcphcpctl/        Entry point for the gcphcpctl binary
pkg/
├── cli/              Root command, version, completion
├── cluster/          Cluster lifecycle commands (create, get, list, delete, login)
├── nodepool/         Nodepool commands (create, get, list, scale, upgrade, delete)
├── auth/             Authentication and token management
├── platformapi/      Platform API client
├── discovery/        Endpoint discovery manifest client and resolver
├── httpdebug/        Invocation-scoped, redacted HTTP metadata tracing
├── regions/          List regions advertised by discovery
├── infra/
│   ├── iam/          IAM infrastructure orchestration and CLI commands
│   └── network/      Network infrastructure orchestration and CLI commands
├── ops/              Operational commands (extractable as plugin)
│   ├── wf/           Workflow management subcommands
│   ├── companion/    AI-powered pod analysis (Vertex AI)
│   └── pam/          Privileged Access Manager commands
├── gcp/
│   ├── iam/          Pure GCP IAM API client wrappers
│   ├── networking/   Pure GCP Compute networking API client wrappers
│   ├── workflows/    Cloud Workflows API client
│   ├── auditlog/     Cloud Audit Log client
│   ├── cloudrun/     Cloud Run API client
│   └── pam/          Privileged Access Manager API client
├── config/           Config file loading
└── output/           Table and JSON output formatting
hack/workflows/       Cloud Workflow YAML definitions

Development

make build    # Build bin/gcphcpctl
make test     # Run unit tests
make lint     # Run go vet
make clean    # Remove build artifacts

Create a release

After merging the release changes into main, run this from a clean repository checkout with upstream pointing to openshift-online/gcp-hcp-ctl and the GitHub CLI (gh) installed and signed in:

./hack/release.sh

Enter the release tag when prompted, for example v0.0.5. The script checks out the latest upstream/main, runs tests, vet, and a local build, then pushes an annotated tag and creates a GitHub Release with generated notes. It leaves the checkout detached at the release commit. Tests run without an inherited GCPHCPCTL_PROJECT; your shell setting is preserved. This script creates the tag and GitHub Release. Build and attach the binaries locally with the steps below.

Build release downloads locally

From macOS or Linux, build Linux, macOS, and Windows binaries for both AMD64 and ARM64 from an existing tag:

./hack/release-build.sh v0.0.5

The helper builds the exact tagged source in a temporary directory without switching your checkout. It requires Go, Git, tar, zip, awk, and either shasum or sha256sum. It ignores inherited Go build flags, workspace overrides, and the personal Go environment file, and pins the compiler to the Go version in the tagged go.mod (Go may download that toolchain). It writes four .tar.gz archives, two Windows .zip archives, and a SHA256 checksum file under bin/releases/v0.0.5/. Each archive contains only the generated executable (gcphcpctl or gcphcpctl.exe); local CLI configuration and authentication files are not copied. Go is cross-compiling: Linux and Windows executables must be tested on their respective operating systems. Archives are created in a fresh staging directory. The completed output replaces the previous release folder only after every build succeeds; previous contents are saved separately under bin/releases/.TAG.previous.*/artifacts/ and are not included in the new packages or checksum file.

Attach the files to the existing GitHub Release:

gh release upload v0.0.5 \
  bin/releases/v0.0.5/gcphcpctl_{linux,mac}_{amd64,arm64}.tar.gz \
  bin/releases/v0.0.5/gcphcpctl_windows_{amd64,arm64}.zip \
  bin/releases/v0.0.5/gcphcpctl_v0.0.5_SHA256SUMS \
  --repo openshift-online/gcp-hcp-ctl

Use the desired release tag in both commands. Building does not create or push tags or upload files, and you can keep an existing release and tag.

Prerequisites

  • Go 1.25+
  • Google Cloud API commands (iam, network, ops) use Application Default Credentials (ADC). For local user credentials, run gcloud auth application-default login; supported service-account or external-account credentials can also be supplied through ADC.
  • Platform API commands (cluster, nodepool) use service-account ADC or external-account ADC with service-account impersonation for identity tokens. With user ADC or no ADC, they instead use the active gcloud session; run gcloud auth login if needed. ADC login alone does not establish that session.
  • Cloud Workflows deployed in the target project/region

Dependency versions

The Gecko platform-api and orlop modules, golang.org/x/exp, and google.golang.org/genproto (including its googleapis/* submodules) have no applicable stable module tags. Their Go pseudo-versions are intentional exceptions to the preference for stable tagged dependencies: each identifies a fixed upstream commit rather than a moving branch. Keep the two Gecko modules pinned to the same reviewed commit and commit go.mod and go.sum together. This exception does not apply to tagged prerelease dependencies or replace compatibility and vulnerability review.

Architecture

The CLI has the following command categories:

  • Cluster lifecycle commands (cluster): Create, inspect, list, delete, and login to clusters via the platform API server. The cluster create flow requires pre-provisioned IAM and network config files from gcphcpctl iam create and gcphcpctl network create. This ensures customers retain full control over network topology, CIDR ranges, and connectivity. The cluster login command configures a kubeconfig context with gcloud exec-based authentication by resolving the cluster's API endpoint from the platform API status data. Cluster lookup supports both name and ID.

  • Nodepool commands (nodepool): Create, inspect, list, scale, and delete nodepools within clusters. Nodepools share the same authenticated client setup, output formatting (text/json/yaml), and name-or-ID resolution patterns as the cluster commands.

  • Infrastructure commands (iam, network): Provision and tear down GCP resources for HyperShift clusters. These live under pkg/infra/ for orchestration logic and pkg/gcp/ for pure GCP API client wrappers. The separation keeps API clients reusable and side-effect-free while command orchestration handles retries, ordering, and user interaction.

  • Operational commands (ops): Debug and remediate running clusters via Cloud Workflows (Zero Operator Access pattern). The ops subtree is self-contained under pkg/ops/ with no dependencies on pkg/cli/, allowing extraction into a standalone plugin binary (gcphcpctl-ops). A stub entry point exists at cmd/ops/main.go for when that separation is needed.

All commands inherit global --project and --region flags from the root command. Environment selection (default production) and explicit endpoint overrides are available through flags, GCPHCPCTL_* environment variables, or config, but are hidden from help. Cluster and nodepool commands require either a discoverable region and environment or an explicit endpoint. Configuration follows the priority: CLI flags > environment variables > config file.

Related Repositories

  • gcp-hcp - Design decisions and architecture
  • gcp-hcp-infra - Terraform infrastructure and ArgoCD configuration

Access management

Access-management commands use the public Platform API and the customer GCP project selected by --project, GCPHCPCTL_PROJECT, or configuration as their namespace. Selecting a project does not grant authority there. Initial service-admin bootstrap is handled by activation/Marketplace, not this CLI.

# Create a custom permission bundle.
gcphcpctl --project customer-project role create limited-operations \
  --permission cluster.get --permission nodepool.get

# Replace the COMPLETE permission set; omitted permissions are removed.
gcphcpctl --project customer-project role update limited-operations \
  --permission cluster.get --permission nodepool.get --permission nodepool.list

# Grant one user a platform role or a custom role, using independent bindings.
gcphcpctl --project customer-project rolebinding create alice-viewer \
  --subject alice@example.com --platform-role cluster-viewer
gcphcpctl --project customer-project rolebinding create alice-limited \
  --subject alice@example.com --role limited-operations

# Audit grants, including full objects in JSON or YAML.
gcphcpctl --project customer-project rolebinding list --subject alice@example.com
gcphcpctl --project customer-project rolebinding get alice-viewer -o yaml
gcphcpctl --project customer-project role list -o json
gcphcpctl --project customer-project role get limited-operations

# Revoke ONLY this named grant; other bindings remain effective.
gcphcpctl --project customer-project rolebinding delete alice-viewer --confirm

Create never overwrites an existing name. Role update uses GET followed by PUT, retaining resourceVersion and metadata; conflicts are returned without retry. Bindings continue to reference the updated Role. Deleting a Role with role delete <name> --confirm does not delete referencing bindings, which can remain unresolved. PlatformRole management and bulk/cross-namespace changes are not supported. A namespace service-admin may deliberately grant any role, including cluster-admin to themselves; the server enforces authorization.

Email normalization preserves local-part case, normalizes Unicode to NFC, and lowercases the domain. Subject filtering uses this exact canonical match.

Successful mutations indicate API acceptance, not globally effective access. Authorization changes may take a moment to propagate globally. The success note is on stdout for text and stderr for JSON/YAML, keeping structured stdout parseable. Structured deletion reports kind, name, namespace, and accepted, not a fabricated deleted object or complete principal revocation.

RoleBinding conditions

Upgrading from raw Cedar conditions: The updated Gecko server ignores legacy raw condition expressions; they are not combined with structured conditions. A binding with only a legacy raw condition therefore becomes unconditional within its existing role and namespace scope. To retain the intended restrictions, update the RoleBinding with structured --condition requirements, or delete and recreate it with structured conditions. Review the translation because arbitrary Cedar expressions may not have a structured equivalent. Verify the resulting allowed and denied access, and keep a separate administrator grant while making access changes. Upgrading the CLI alone does not change server-side enforcement.

Each repeatable --condition supplies one requirement. Requirements are ANDed, including repeated keys; values within an In requirement are alternatives. Keys are case-sensitive name or region; operators are In and NotIn. Set operators require ASCII JSON whitespace on both sides and a nonempty JSON array of double-quoted strings. Only In and NotIn are supported; scalar ==/!= syntax is rejected. Blank strings, nulls, empty arrays, trailing input and raw policy expressions are rejected locally before network discovery or authentication. Accepted contents, order and duplicates are preserved; no name/region identifier validation is performed locally.

# Two requirements, ANDed; alternatives within a requirement.
gcphcpctl --project customer-project rolebinding create regional-viewer \
  --subject alice@example.com --platform-role cluster-viewer \
  --condition 'region In ["us-east1", "europe-*"]' \
  --condition 'name In ["demo-*"]'

# Replace the complete list, not append.
gcphcpctl --project customer-project rolebinding update regional-viewer \
  --condition 'region NotIn ["us-central1"]'

# Clear restrictions, broadening this grant.
gcphcpctl --project customer-project rolebinding update regional-viewer --clear-conditions

# Preserve conditions during an unrelated update.
gcphcpctl --project customer-project rolebinding update regional-viewer --subject bob@example.com

Shell single quotes protect JSON quotes, spaces, commas and stars; apostrophes in values require appropriate shell escaping. * is the only wildcard, matching zero or more characters, case-sensitively over the whole value. JSON "\u002a" also means a wildcard; "\\*" means backslash followed by wildcard, while "\*" is invalid JSON. There is no literal-star escape or regex syntax.

No conditions on create means unconditional; omission on update preserves. Adding a requirement requires resupplying all requirements to retain. --condition '' is invalid, not clearing. --clear-conditions=false does not clear or count as an update; combining it with --condition is still invalid. Update uses one JSON Merge Patch: omitted conditions preserve, a populated array replaces, and conditions: [] clears. No preliminary GET is performed.

Details show canonical JSON-array Conditions as a - bulleted list. Requirements remain ANDed; the display does not change authorization semantics. List retains its bounded escaped preview; JSON/YAML retain native structured resources. Display text is not guaranteed shell-ready. The server validates the complete requirements and generated expression length; CLI syntax validation does not prove an authorization outcome.

Safety: Independent grants remain additive; exclusions are not global denies. Region conditions do not match non-regional resources. There is no CLI resource-type exemption. Keep a separate administrator grant to avoid access-management lockout. Changes may take time to propagate.

For live acceptance, use a disposable binding: create/get/list with both keys, operators and repeated keys; update an unrelated field, replace, clear, and replace again. Verify direct API rejection of empty requirement values separately from valid top-level clearing. Check normalized errors, expression-length rejection and conflicts, then delete only disposable resources. Record server revision and distinguish API acceptance from observed authorization behavior.

Manual access-management acceptance

Use a disposable customer project with a bootstrapped service-admin, a separate user principal, and a second project for namespace-isolation checks. Confirm the deployment exposes public roles/rolebindings routes and enables Cedar before running these tests. Never delete bootstrap bindings or revoke the sole admin.

  1. Create a custom Role and grants as above; inspect list/get in text, JSON and YAML. Repeat a create name and verify conflict without overwrite.
  2. As the separate viewer, poll a safe read every 5 seconds for up to 2 minutes; verify reads become permitted and writes remain denied. Record acceptance and observed convergence separately; one replica is not proof of global convergence.
  3. Update a custom Role in place and verify omitted permissions eventually stop working and new permissions work, without changing the binding identity.
  4. Create two independent grants for the principal, delete one by name, and verify the other still works. Delete the final relevant grant and observe eventual denial using the same bounded polling window.
  5. Verify a viewer cannot manage access resources and project-A grants do not authorize project-B operations. On disposable resources, verify service-admin can deliberately bind cluster-admin to themselves.
  6. Submit a stale-resourceVersion Role PUT through an integration harness and verify conflict; verify invalid permissions/references produce safe errors.
  7. Clean up only test-owned bindings and Roles with confirmed named deletes.

If convergence is not observed within the bounded window, record the timeout rather than claiming success. Live testing requires explicit test identities and project selection; unit tests do not use live credentials.

Discover platform roles

gcphcpctl platformrole list --env integration --region us-central1
gcphcpctl platformrole get cluster-viewer --env integration --region us-central1
gcphcpctl platformrole get service-admin --api-endpoint https://API_HOST -o yaml
gcphcpctl platformrole list --env integration --region us-central1 -o json

All authenticated users can discover system-managed PlatformRoles and their complete permission sets, without a RoleBinding or additional discovery grant. The commands are read-only and always use platform-scoped public API paths. Project values from --project, GCPHCPCTL_PROJECT, or config are accepted but ignored; they do not filter the catalog. Environment and region still select the service instance. Namespaced commands such as role and rolebinding continue to require a project.

Lists aggregate up to 100 pages. Repeated continuation tokens or a catalog requiring more pages return an error without partial output.

An explicit API endpoint from flag/environment/config overrides discovery and works without an OIDC issuer or a discovery request. Otherwise --env and --region resolve the API endpoint through the normal discovery manifest. List text shows NAME, PERMISSIONS (count), and AGE; get text shows every permission. JSON/YAML retain the public Kubernetes resource shape and full permissions, but item metadata is minimized to name and creation timestamp (no managed fields, GitOps annotations, labels, or internal metadata).

The server and ESPv2 Endpoints configuration must both support the new routes. 401/403/404 use the shared fixed errors (not authenticated, permission denied, not found); the CLI does not infer a missing grant or fall back to the private API. Role definitions continue to be managed privately through Helm.

Discovery uses the public PlatformRole types from the Gecko API SDK. Existing upgrade-policy commands keep their Cluster maintenance behavior. The public server and gateway still need the PlatformRole discovery endpoints.

About

CLI tool for managing GCP Hosted Control Planes

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages