Describe an app in typed Python¶
This page shows how to describe an application’s Deployments, StatefulSets,
DaemonSets, Jobs and CronJobs, Services, configuration, secrets, service
accounts with their permissions, pod security defaults, network policies,
autoscalers, disruption budgets, Ingresses and Gateway API HTTPRoutes with
typed Python objects, and
how to render them to manifests or release them, with no manifest dicts or YAML.
Objects of any other kind, custom resources included, are declared with
app.resource(...) and a spec generated from their CRD (see Custom resources and any other kind);
one module can describe dev, staging and prod with typed overrides (see
Environments: one app for dev, staging and prod).
Maturity: preview
piceli.app and piceli render are preview: they are tested and used by
the release example, but names and defaults may still change before 1.0.
The manifests they render are plain Kubernetes objects and do not depend on
Piceli at runtime.
Prerequisites¶
Piceli installed (
pip install piceli) and Python 3.12 or later.To release the app, a
release.tomlas described in Releases from a spec (piceli release). Rendering needs no cluster and no spec.
Steps¶
Declare the app. Create a module with a function of the release context.
App(name)collects declarations, and each declaration is validated as soon as you make it. This isexamples/typed_app/app.py:from __future__ import annotations from piceli import App, ExistingClaim, Resources from piceli.k8s.release_spec import ReleaseContext def build(ctx: ReleaseContext) -> App: app = App("shop") password = app.secret("cache-password", {"password": ctx.secret("cache-password")}) cache = app.deployment( "cache", image=ctx.image("cache"), command=["sh", "-c", 'exec redis-server --requirepass "$REDIS_PASSWORD"'], ports=[6379], ready=app.probe.tcp(6379), env={"REDIS_PASSWORD": password.key("password")}, volumes={"/data": ExistingClaim("cache-state")}, # never managed resources=Resources(cpu="100m", memory="128Mi", memory_limit="256Mi"), strategy="Recreate", ) api = app.deployment( "api", image=ctx.image("api"), ports=[8080], ready=app.probe.http("/healthz", 8080), env={"CACHE_PASSWORD": password.key("password")}, ) app.service(cache, port=6379) app.service( api, port=80, target_port=8080, # How to reach it from a laptop; renders to no Kubernetes object. access=app.access.forward(local=18080, health="/healthz"), ) app.network_policy(cache, allow_from=[api], ports=[6379]) app.depends(api, on=cache) # Return the App (not app.composition(ctx)) so `piceli access` and # `piceli status` can read its access declarations. return app
ctxis the release context:ctx.image(name)is the image pinned by digest inrelease.toml,ctx.secret(name)is an opaque reference to a generated secret,ctx.valuesholds the public[values]table andctx.nodesholds the verified nodes.Render it without a cluster.
piceli render --spec examples/typed_app/release.toml piceli render examples/typed_app/app.py:build --spec examples/typed_app/release.toml --format json
The spec supplies the namespace, images, secret inputs (as placeholders), values and nodes, and names the composition (
[release] composition = "app.py:build"). Without--spec,piceli renderaccepts anAppobject (path/to/app.py:app) or a composition function that needs no images or secrets, and uses--namespace(defaultdefault). AnAppalone knows no nodes, so anode="alias"pin is refused there; render thePipelineinstead (path/to/app.py:pipeline, see Deploy an app from source), which uses its target’s namespace and declared nodes.Release it. Run
piceli release plan --spec examples/typed_app/release.toml(after pointing[target]at your cluster) and apply the plan hash it prints, as described in Releases from a spec (piceli release).
Expected output¶
piceli render prints one YAML document per object, grouped by component.
Secret data is shown as <redacted>:
---
# component: api (depends on: cache, cache-password)
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: api
app.kubernetes.io/part-of: shop
name: api
namespace: shop
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: api
…
With --format json, it prints one object:
{"state": "rendered", "namespace": …, "components": [{"name", "dependencies", "resources": [{"manifest", "secret_bindings": [{"pointer", "input"}]}]}]}.
If it fails¶
A
ValidationErrorat declaration. The message names the model and field, for examplereplicas: Input should be greater than or equal to 0. Fix the argument. Unknown keyword arguments are rejected, so a typo fails here too.unknown image 'x'orunknown secret input 'x'. The function reads an image or secret that the spec does not declare. Pass--spec, or declare it under[images]or[secrets].pinned to node 'gpu', which the target does not declare. Add[target.nodes.gpu]to the spec.depends() names unknown components. Adependsargument names a component that nothing declares.mounted as an ExistingClaim and must never be managed. The same claim is also created by the composition, for example by an added template. Remove one of them.
piceli render exits with 2 for every rejection and prints
{"state": "rejected", "reason": …, "message": …} to stdout, whatever
--format says (the explanation goes to stderr). The reason is
render-target-invalid (the target or the spec could not be loaded) or
render-model-invalid (the model failed to render).
A complete example¶
A realistic app: dev, staging and prod from one typed module walks through examples/reference/app.py: every kind on
this page, a custom resource and a SOPS secret in one module, deployed to
dev, staging and prod with typed environment overrides.
examples/release/composition.py is the release example as a typed model.
It renders byte for byte the same resource intents as the dict-based
composition it replaced (a unit test compares the canonical JSON):
from piceli import App, ConfigVolume, SecretVolume
from piceli.k8s.ops import DeploymentComposition
from piceli.k8s.release_spec import ReleaseContext
def build(ctx: ReleaseContext) -> DeploymentComposition:
app = App("web", labels={"app.kubernetes.io/name": "web"})
config = app.config(
"web-config",
{"greeting": str(ctx.values.get("greeting", "hello"))},
component="config",
)
token = app.secret(
"web-token", {"token": ctx.secret("api-token")}, component="config"
)
tls = app.secret(
"web-tls",
{"tls.crt": ctx.secret("web-tls.crt"), "tls.key": ctx.secret("web-tls.key")},
type="kubernetes.io/tls",
component="config",
)
app.deployment(
"web",
image=ctx.image("web"),
replicas=int(ctx.values.get("replicas", 1)),
ports=[80],
env={"API_TOKEN": token.key("token")},
volumes={
"/etc/web": ConfigVolume(config, name="config"),
"/etc/web-tls": SecretVolume(tls, name="tls"),
},
)
return app.composition(ctx) # "web" depends on "config": it reads its objects
Rules the model enforces¶
Components and ordering¶
A release applies components in dependency order and waits for each one to become ready before the next. Every declaration belongs to a component:
Declaration |
Default component |
|---|---|
|
|
|
|
|
the workload’s component |
|
the first route’s Service component, else |
|
|
|
|
Pass component= to group objects, as the example does with config. A
workload automatically depends on the component of every config and secret
of the app that it reads through env or volumes, and of the service account it
is bound to. app.depends(a, on=b) adds
other edges. It accepts declared objects or component names.
Within a release, kinds are also applied in a fixed order unless a dependency
says otherwise: Deployments, StatefulSets and DaemonSets, then Services, then
Jobs and CronJobs, then Ingresses, HTTPRoutes, NetworkPolicies, disruption
budgets and autoscalers. app.depends(api, on=migrate) makes a Job run (to
completion) before a Deployment instead.
Selector labels are chosen once¶
A workload’s spec.selector is immutable in Kubernetes. Piceli derives it
from the workload’s own name only (a Job’s selector is chosen by Kubernetes;
its pods still carry the label):
selector = {"app.kubernetes.io/name": <deployment name>} # unless selector= is given
Renaming the app, moving the Deployment to another component, or changing app
or Deployment labels never changes the selector of an existing Deployment. The
pod labels always include the selector. To change a selector, create a
Deployment with a new name. If an existing Deployment’s selector changes
anyway (through an explicit selector=), the API server rejects the apply
instead of orphaning pods.
Object labels default to {"app.kubernetes.io/part-of": <app name>} on every
object. App(name, labels={…}) replaces them.
Existing claims are never managed¶
ExistingClaim("name") mounts a PersistentVolumeClaim that already exists. It
produces no resource intent, so no plan can create, change, adopt or delete
the claim, and rendering refuses a composition that also manages a claim with
that name. The claim must exist before the pod starts; otherwise the pod stays
Pending. PersistentVolumeClaims that a release does manage are a retained
kind: a release never prunes them either.
Secret values never reach the model¶
app.secret(name, {key: ctx.secret(...)}) accepts only opaque secret
references. The executor resolves them at apply time. Env values reference a
Secret key (secret.key("password")). Passing a secret reference or a plain
string as a Secret value is a validation error. Put public values in
app.config(...).
Nodes come from the target¶
node="primary" pins the pods to the verified node declared under
[target.nodes.primary] (nodeSelector: kubernetes.io/hostname), or under
nodes= of a pipeline’s Target. piceli release and piceli deploy
verify the node against the cluster. piceli render uses the name declared
in the spec, or in the Target when the target is a Pipeline.
Access is declared, never rendered¶
app.service(web, port=3000, access=app.access.forward(local=18080, path="/login")) declares how to reach the Service from a laptop. It adds
nothing to the manifests; piceli status and piceli access use it (see
Reach your services from your laptop). For them to see it, the composition function returns the App
itself, as examples/typed_app/app.py does; a release renders a returned App.
Apply pod defaults to every workload¶
Settings that every pod of an app shares (a non-root user, a seccomp profile, an extra node selector, a grace period) are declared once on the App:
from piceli import App, PodDefaults, Security
app = App(
"shop",
pod_defaults=PodDefaults(
security=Security.restricted(user=10001, fs_group=10001),
node_selector={"kubernetes.io/arch": "amd64"},
termination_grace_seconds=30,
),
)
api = app.deployment("api", image=ctx.image("api"))
web = app.deployment(
"web",
image=ctx.image("web"),
node="primary",
security=Security(read_only_root_filesystem=True),
)
Every workload declared on the app (Deployment, StatefulSet, DaemonSet, Job, CronJob) renders:
Setting |
Rendered as |
|---|---|
|
the pod’s |
|
the |
|
|
|
|
|
|
Security.restricted(...) passes the Kubernetes restricted Pod Security
Standard: non-root user and group, the runtime’s default seccomp profile, no
privilege escalation and every capability dropped.
Layering, from lowest to highest:
pod_defaults;the workload’s own
security=,node_selector=,termination_grace_seconds=andautomount_token=.securitywins field by field (a workload’sSecurity(run_as_user=2000)keeps the defaultfs_group),node_selectorkey by key, the others as a whole;app.override(workload, patch), applied to the rendered manifest last (aNonein the patch removes a default).
Rules:
A
node_selector(from the defaults or the workload) that setskubernetes.io/hostnameis refused on a workload withnode=: pin withnode=or select the host by label, not both. The error names the workload and where the key came from.Security(run_as_non_root=True, run_as_user=0)is refused, and aLocalhostseccomp profile needsseccomp_localhost_profile.Without
pod_defaultsand the new workload arguments, rendering is exactly what it was.Components added with
app.add(...)are not changed.
Give a workload API permissions¶
A workload that reads the Kubernetes API (a watcher, an operator) needs a ServiceAccount and RBAC objects. Declare them with typed rules and bind the account to the workload:
from piceli import Rule
watcher = app.service_account(
"watcher",
rules=[Rule(resources=["pods", "pods/log"], verbs=["get", "list", "watch"])],
cluster_rules=[Rule(resources=["nodes"], verbs=["get", "list"])],
)
app.deployment("watcher", image=ctx.image("watcher"), service_account=watcher)
This renders:
Object |
Name |
When |
|---|---|---|
ServiceAccount |
|
always |
Role and RoleBinding |
|
with |
ClusterRole and ClusterRoleBinding |
|
with |
Rule(resources=…, verbs=…, api_groups=("",), resource_names=()) is checked
when it is declared: resources, verbs and api_groups must not be empty,
verbs and resources must be well-formed, and resource_names cannot be
combined with create or deletecollection (Kubernetes cannot restrict those
by name). A "*" anywhere is refused unless the rule says
allow_wildcard=True, because a wildcard also grants whatever Kubernetes adds
later.
Tokens: the ServiceAccount renders automountServiceAccountToken: false, and
a pod bound to it with service_account= renders true. Only the pods you
bind get API credentials, even if another pod names the account. A pod bound
to an account the app does not declare (service_account="name") keeps the
Kubernetes default. Set PodDefaults(automount_token=False) to keep tokens out
of every pod that is not bound to a declared account, and
automount_token= on a workload to decide for that workload alone.
app.override(watcher, patch) patches the ServiceAccount; the Role and
binding objects follow from the rules.
Cluster-scoped objects in a release¶
A ClusterRole and a ClusterRoleBinding are not in any namespace: every
release in the cluster sees them. piceli release handles them like this:
Names are unique per namespace.
<namespace>:<app>:<account>cannot collide between two namespaces (RBAC names accept:).Ownership is per namespace. An object counts as this release’s only when it carries this release’s owner (
piceli.io/owner) andpiceli.io/namespace: <release namespace>. The same owner released in another namespace is someone else: its objects are never changed or pruned, and one with a conflicting name must be adopted explicitly (--adopt ClusterRole/<name>, which a takeover restamps).Plans show them. Each such action carries
"cluster_scoped": truein the JSON plan and[cluster-scoped]in the text; approving the plan hash approves them like any other action.Prune and rollback clean them up. With
[release] prune = true, droppingcluster_rules(or the account) deletes exactly this release’s ClusterRole and ClusterRoleBinding; a rollback to a release that had them recreates them.RBAC and declared resources. Besides ClusterRoles and ClusterRoleBindings, a release manages other cluster-scoped objects only when they carry
piceli.io/namespace(asapp.resource(..., scope="cluster")renders them, see Custom resources and any other kind); Namespace, PersistentVolume and CustomResourceDefinition are always refused withinvalid-composition. A hand-built ClusterRole or ClusterRoleBinding in a composition is stamped withpiceli.io/namespace; one that names another namespace is refused.The deployer needs cluster rights. Planning lists ClusterRoles and ClusterRoleBindings cluster-wide, and applying writes them, so the kubeconfig user needs those permissions (and Kubernetes only lets it grant permissions it holds). Without them, discovery is incomplete and the plan is refused.
Restrict traffic with network policies¶
app.network_policy(workload, allow_from=[…], ports=[…]) protects one
workload’s pods. To select pods by label instead, pass selector= and a
name=; allow_from_selector= adds sources by label (one mapping or a list):
app.network_policy(
selector=app.release_selector,
allow_from_selector=app.release_selector,
name="shop-internal",
)
app.network_policy(api, allow_from_selector={"role": "gateway"}, ports=[8080])
app.release_selector is the set of labels every pod of the app carries (the
app’s object labels, {"app.kubernetes.io/part-of": <app name>} by default),
so the first policy lets only this app’s pods reach its pods. An empty
selector is refused: it would match every pod in the namespace.
Egress, namespaces and CIDRs¶
egress=[…] restricts where the selected pods may connect. List workloads of
the app (every port) or typed rules. NetworkRule(peers=[…], ports=[…]) takes
peers built with NetworkPeer.pods(labels), NetworkPeer.workload(w),
NetworkPeer.namespace("prod") (by name) or
NetworkPeer.namespace(labels={…}, pods={…}) (by label, optionally only some
pods of those namespaces), and NetworkPeer.cidr("10.0.0.0/8", except_=["10.1.0.0/16"]). Ports are numbers (TCP) or
NetworkPort(port=6000, end_port=6010, protocol="UDP"). ingress=[…] takes
the same rules, so ingress can select namespaces too.
from piceli import NetworkPeer, NetworkPort, NetworkRule
app.network_policy(
api,
egress=[
db, # a workload of this app
NetworkRule(
peers=[NetworkPeer.cidr("10.0.0.0/8", except_=["10.1.0.0/16"])], ports=[443]
),
NetworkRule(
peers=[NetworkPeer.namespace("metrics")], ports=[NetworkPort(port=4317)]
),
],
allow_dns=True,
)
Egress deny also blocks DNS. Once a pod is selected by an Egress policy,
everything not listed is denied, including name resolution. Pass
allow_dns=True (or add NetworkRule.dns(), which allows kube-dns in
kube-system on port 53 UDP and TCP) unless the pods need no DNS.
policy_types is derived: Ingress for a policy without egress (rendered
exactly as before, so existing plan hashes do not change); Egress when it
declares egress and no ingress arguments; both when it declares both. Give it
explicitly to override, for example
app.network_policy(api, policy_types=["Egress"]) denies all egress of api.
Policies are additive: a pod selected by several policies may do whatever any
of them allows, so an egress cut needs no other policy that allows the
traffic. A CIDR, port, protocol, empty selector or rule with neither peers nor
ports is refused when the app is built (render-target-invalid, whose message names the problem), and a
workload in egress= must be declared in the same app. Enforcement needs a
CNI that implements NetworkPolicy (kind’s default does).
Scratch space: in memory or on disk¶
Two volumes give a pod a scratch directory that is lost when the pod stops.
MemoryVolume keeps it in RAM (emptyDir with medium: Memory) and counts
against the container’s memory limit. ScratchVolume (0.36.0) keeps it on the
node’s disk, for data too large for RAM:
downloads = ScratchVolume(size_limit="2Gi")
app.deployment(
"web",
image=ctx.image("web"),
volumes={"/srv/downloads": downloads},
init=[
Container(
name="fetch",
image=ctx.image("tools"),
command=[
"piceli",
"artifacts",
"fetch-file",
"--from",
"oci://...",
"--digest",
"sha256:...",
"--out",
"/srv/downloads/app.tar",
],
volumes={"/srv/downloads": downloads},
)
],
)
The init container fills the folder by digest and the app serves it. It renders
emptyDir: {sizeLimit: 2Gi}. On disk, size_limit counts against the node’s
ephemeral storage: a pod that writes more is evicted.
Files from an image¶
FilesImage (0.40.0) gives a pod a folder of files that a build put in an
image, such as site builds an app serves. The files are part of the image,
so they are keyed by its digest: a new build is a new digest, and the pods
roll.
The image only carries the files. A host build can make it from a pinned busybox base (see Builds without a VM):
[[output.image]]
name = "site-builds"
repository = "shop/site-builds"
base = { image = "docker.io/library/busybox:1.37", digest = "sha256:…" }
shared_files = { "site" = "/data" }
Mount it like any volume:
from piceli import Build, FilesImage
images = Build.spec("host-build.toml", builder="host")
app.deployment(
"web",
image=images["server"],
volumes={"/srv/builds": FilesImage(images["site-builds"], size_limit="2Gi")},
)
This renders:
a disk
emptyDir(withsizeLimitwhensize_limitis set), asScratchVolumedoes;an init container
files-<volume>with that image, runningcp -a /data/. /piceli-files/(path=picks another folder of the image). It runs before the workload’s own init containers, so they can read the files too;a read-only mount in every container that mounts the volume.
The image takes the same path as any container image: a build handle becomes
the delivered reference, a mirrored image its copy, and both are pinned by
digest. The init container gets the workload’s security settings, under
locked-down defaults (no privilege escalation, every capability dropped,
read-only root filesystem); when a container of the pod declares resources,
it gets small ones too (resources= sets others). Give the volume a name=
to share one copy between mounts at different paths.
Two things to know:
The image needs a
cp: a pinned busybox base is enough.The copy runs once per pod start, so large folders slow the start. Kubernetes image volumes (
volumes[].image, on by default only from Kubernetes 1.35) mount an image without a copy; they may become an option later.
Stateful workloads¶
app.stateful_set(...) takes the same pod and container arguments as
app.deployment(...). Mount a ClaimTemplate to give each pod its own
PersistentVolumeClaim:
from piceli import ClaimTemplate
db = app.stateful_set(
"db",
image=ctx.image("db"),
ports=[5432],
replicas=3,
volumes={"/var/lib/db": ClaimTemplate("data", size="1Gi")},
pod_management="Parallel", # or "OrderedReady" (default)
update_strategy="RollingUpdate", # or "OnDelete"
)
Headless Service. By default the app also declares a headless Service (
clusterIP: None) named after the StatefulSet (orservice_name=) that selects its pods and exposes the main container’s ports (namedport-<number>when there are several);serviceNamepoints at it, so each pod is reachable as<pod>.<service>. Passheadless=Falseto pointservice_name=at a Service declared elsewhere, or to have none. Declare a regular Service in front of it withapp.service(db, port=…, name=…).Claims are never pruned. The claims come from the StatefulSet controller (
<template>-<name>-<ordinal>), not from the release: no plan creates, changes, adopts or deletes them. The StatefulSet renderspersistentVolumeClaimRetentionPolicy: {whenDeleted: Retain, whenScaled: Retain}, and a release deletes (prune) or replaces a StatefulSet withOrphanpropagation, so the claims and their data outlive it; a later release (or a rollback) that declares the StatefulSet again reattaches its pods to the same claims. Delete claims yourself when the data is no longer needed.Immutable fields.
service_name,pod_management, the selector and the claim templates cannot change on an existing StatefulSet (see Immutable fields). AClaimTemplateis only accepted on a StatefulSet.
Jobs, CronJobs and DaemonSets¶
migrate = app.job(
"migrate",
image=ctx.image("api"),
command=["migrate"],
backoff_limit=2,
active_deadline_seconds=600,
)
api = app.deployment("api", image=ctx.image("api"), ports=[8080])
app.depends(api, on=migrate) # run the migration before the API rolls out
app.cron_job(
"report",
schedule="0 3 * * *",
time_zone="Etc/UTC",
image=ctx.image("api"),
command=["report"],
concurrency="Forbid",
)
app.daemon_set(
"agent", image=ctx.image("agent"), node_selector={"kubernetes.io/os": "linux"}
)
A release waits until a Job completes (a failing Job times out the release).
restart_policyisNever(default) orOnFailure. A Job has noselector=: Kubernetes chooses it. Withttl_seconds_after_finished, the Job is deleted after it finishes and the next release creates (and runs) it again.A CronJob is ready as soon as it exists. The Jobs it creates belong to it and are never managed or pruned by a release. Every field may change; new Jobs use the new template.
A DaemonSet runs one pod on every node that matches its node selector (and the app’s
pod_defaults.node_selector); a release waits until every scheduled pod is ready and updated.
Roll pods when their configuration changes¶
A container reads its environment once, when it starts, and many programs read a mounted file only once too. Kubernetes rolls a Deployment, StatefulSet or DaemonSet only when its pod template changes, so a changed ConfigMap or Secret would otherwise reach the pods only at their next restart: a server keeps the old password and refuses every client.
Piceli puts a digest of the content the pods read on the pod template of
every Deployment, StatefulSet and DaemonSet. It covers the ConfigMaps and
Secrets of the same release that the pods read through a volume, a
projected volume, envFrom or env.valueFrom (in any container, init
containers included):
Pod template annotation |
Digest of |
|---|---|
|
|
|
|
A changed value rolls the pods; an unchanged one does not. A value carried over to a new release gets a new private version but the same fingerprint, so a release that changes something else leaves the consumers alone, and planning the same release again is a no-op.
No value leaks. A value’s fingerprint is an HMAC-SHA256 under a random key that Piceli creates once in the private secret store (
secrets.sqlitein the state directory) and that never leaves it; the annotation is a digest of those fingerprints. Without the store it says nothing about a value, short passwords included. A new store (a new state directory) means a new key: every consumer rolls once.Offline renders (
piceli render,piceli bundle, a chart) have no values: they use the opaque secret reference instead, so theirsecrets-digestis stable for a given output name and only shows that a workload reads a Secret.piceli release diffof a new release keeps the livesecrets-digestfor the same reason (it never reads secret values), while the plan computes the real one.The plan’s evidence is for the final template. A plan observes the cluster before it reads any value, so the server dry runs it captures first carry the offline digest; once the values are read, the workloads whose
secrets-digestchanged are dry-run again with the real one. The plan then compares exactly what it applies, server defaults included.Only content the release declares counts. A Secret created by another tool is not hashed: Piceli cannot see its content. Neither is a Secret or ConfigMap the release declares with its metadata only (adopted without its value): adopting it leaves its consumers’ pod templates as they are.
Jobs and CronJobs carry no digest. Every run starts new pods that read the current content, and a Job’s pod template is immutable.
Raw compositions get it too. The release engine annotates every workload of any composition the same way.
Turn it off for a workload that reloads its configuration itself:
app.deployment("proxy", image=ctx.image("proxy"), volumes=..., roll_on_change=False)
roll_on_change=False (also on stateful_set and daemon_set) declares
piceli.io/roll-on-change: "false" on the object; the release engine (and
piceli render) reads it, adds no digest and removes the marker, so the
live object never carries it. A raw composition opts out with the same
annotation.
Upgrading to a Piceli version with these digests adds them to the pod templates on the next release: every workload that reads a ConfigMap or Secret of its release rolls once.
Autoscale a workload¶
from piceli import Resources
api = app.deployment(
"api",
image=ctx.image("api"),
ports=[8080],
resources=Resources(cpu="100m", memory="128Mi"),
)
app.autoscaler(api, min_replicas=2, max_replicas=10, cpu=70)
app.autoscaler(workload, …) declares a HorizontalPodAutoscaler
(autoscaling/v2) for a Deployment or StatefulSet. cpu and memory are
target average utilizations in percent of the requests, so every container
of the workload must request that resource (checked when declared).
Replicas rule: the autoscaler owns the replica count.
The workload must not set
replicas=(refused when declared). It renders the autoscaler’smin_replicasasspec.replicas, which is only its initial size: a new workload starts at the minimum.Once the workload exists, the plan declares the live count while Piceli still owns the field (
held), and leaves the field out once the HPA has scaled it (yielded); it never removes/spec/replicas. A release therefore never resets the HPA’s count, and a workload that hadreplicasin an earlier release keeps its live count.The HPA’s changes are not a difference: the next plan is a no-op.
release plan --jsonreports the mode underautoscaled.
The same rule applies to an HPA in plain manifests or created by another tool; see Compatibility and shared ownership.
Only one autoscaler per workload. Metrics need a metrics server in the
cluster; without one the HPA still enforces min_replicas. An environment
changes the bounds with autoscalers={"api": Scaling(min_replicas=3, max_replicas=20)} (see Environments: one app for dev, staging and prod).
Limit disruptions¶
app.disruption_budget(api, max_unavailable=1)
app.disruption_budget(db, min_available="50%", name="db-budget")
A PodDisruptionBudget (policy/v1) selects the workload’s pods (a
Deployment, StatefulSet or DaemonSet). Pass exactly one of min_available
and max_unavailable, as a pod count or a percentage;
unhealthy_pod_eviction= sets unhealthyPodEvictionPolicy.
Route HTTP traffic¶
A Route(service, path) is one path to a Service port. With a declared
Service handle the port is filled in (and checked); a Service the app does not
declare needs port=.
from piceli import GatewayRef, Route
web_service = app.service(web, port=80, target_port=3000)
app.ingress(
"shop",
hosts=["shop.example.com"],
class_name="nginx",
tls_secret="shop-tls",
routes=[Route(web_service, "/"), Route(api_service, "/api", port="http")],
)
app.http_route(
"shop",
gateway=GatewayRef("public", namespace="gateways", section="https"),
hosts=["shop.example.com"],
routes=[Route(web_service, "/"), Route(api_service, "/api", port=8080)],
)
app.ingressrenders anetworking.k8s.io/v1Ingress; every host serves every route, and no hosts means any host. It needs an ingress controller to carry traffic, not to be released.app.http_routerenders a Gateway APIHTTPRoute(gateway.networking.k8s.io/v1), one rule per route, attached to one or more Gateways (a name in the release namespace, or aGatewayRef). Backend ports are numbers. The Gateway API CRDs must be installed in the cluster; they are not part of Kubernetes. Rendering needs nothing, but without the CRDs a plan is refused because the kind cannot be discovered. Install them from a pinned release, for examplekubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.2.1/standard-install.yaml.A release waits only until an Ingress or HTTPRoute exists, not until a controller accepts it.
Immutable fields and replace¶
Some fields never change on an existing object: a Job’s pod template and
completions, and a StatefulSet’s serviceName, podManagementPolicy,
selector and claim templates. Piceli never works around this implicitly.
When a composition changes one of them, piceli release plan refuses with
immutable-field-changed and names the object:
rejected: Job/migrate: immutable fields would change (spec.template); the API server refuses the update [immutable-field-changed]
blocking Job/migrate: … -> --replace Job/migrate
Plan again with --replace Job/migrate (or [release] replace) to delete the
object and create it from the release, after a restorable backup (see
Releases from a spec (piceli release)). A replaced Job’s pods are deleted with it and the new Job
runs; a replaced StatefulSet is deleted with Orphan propagation, so its
pods keep running until the new StatefulSet adopts (and, for a changed
template, rolls) them, and its claims are kept. An existing claim keeps its
size: a changed claim template applies only to new claims.
Reusing templates¶
app.add(...) includes a component built elsewhere: a DeploymentComponent,
or a template with a component(namespace) method such as
NodeLocalRegistry:
app.add(templates.NodeLocalRegistry(node_name=ctx.nodes["primary"].name))
app.depends(web, on="registry")
API reference¶
Grouped by task. Every class is a frozen pydantic model with its parameters documented in the API docs.
Task |
Types |
|---|---|
Collect and render an app |
|
Any other kind, custom resources (Custom resources and any other kind) |
|
Environments (Environments: one app for dev, staging and prod) |
|
Pod settings |
|
Permissions |
|
Containers |
|
Health checks |
|
Environment |
|
Volumes |
|
HTTP routing |
|
Declared objects (returned handles) |
|
Everything above is importable from piceli directly (from piceli import App, ExistingClaim). The exports are lazy, so import piceli stays cheap and
has no side effects.
piceli render contract¶
piceli render [TARGET] [--spec release.toml] [--namespace NS] [--format yaml|json]
[--env NAME [--diff-env OTHER]] [--out DIR [--secrets refuse|external]]
|
|
|
A |
|
Overrides the namespace (default: the spec’s namespace, otherwise |
A |
Renders the app as |
|
|
|
Renders one environment of the App (new in 0.7.0, see Environments: one app for dev, staging and prod); a |
|
With |
|
Writes one YAML file per object into |
|
With |
Side effects |
Imports the target module and reads the spec and the receipts it names. It never contacts a cluster or reads a kubeconfig, never reads or generates secret values and writes files only with |
Retry |
Always safe. |
Approval |
None. |
Exit codes |
|
Not typed yet¶
Tolerations, affinity and topology spread constraints are not part of App
yet, nor are other kinds (custom resources, other Gateway API routes). In the
meantime:
declare a whole object of any kind with
app.resource(api_version, kind, name, spec)(Custom resources and any other kind): a typed spec generated from a CRD, or a JSON mapping;set a field of a declared object with
app.override(obj, patch): the patch is merged into the rendered manifest (mappings key by key,Noneremoves a key, lists of objects with a uniquenamemerge onname, other values replace). It cannot change the object’s identity or a Secret’s data;api = app.deployment("api", image=ctx.image("api"), container="server") app.override( api, { "spec": { "template": { "spec": { "tolerations": [{"key": "dedicated", "operator": "Exists"}], } } } }, )
for a whole component built elsewhere, build a
DeploymentComponentfromResourceIntentobjects (or from the templates) and include it withapp.add(...).
container= names the main container when it must not be named after the
Deployment. piceli import (From kubectl scripts to Piceli) generates both
forms from live objects.