A realistic app: dev, staging and prod from one typed module¶
This page walks through examples/reference/app.py, a complete application
described in one typed Python module and deployed to three environments: web
and api Deployments with an autoscaler and a disruption budget, a Redis
StatefulSet with its own volume per pod, a Job and a CronJob, a Gateway API
HTTPRoute, a cert-manager Certificate, a network policy, a ServiceAccount
with RBAC, restricted pods, a password from a SOPS file and post-deploy
checks. There is no YAML, no manifest dict and no app.override(...) in it:
every object and every difference between environments is typed and checked
when it is declared.
Maturity: preview
The example uses preview features (typed apps, environments, custom
resources, external secret sources). It is tested on every change: the
three environments are rendered and compared in unit tests, dev is deployed
to a fake API server in acceptance tests and to a kind cluster in CI.
Prerequisites¶
Piceli 0.7.0 or later,
kubectl, andsopsonPATH(to decrypt the store password; rendering does not need it).To deploy
dev: a disposablekindcluster, the Gateway API CRDs and the cert-managerCertificateCRD (no controller is needed: the HTTPRoute and the Certificate are only stored). Nothing is built: the images are small public images pinned by digest.
Warning
examples/reference/secrets/example-only.agekey is a public age key,
committed so that the example and its tests run offline. Never use it, or
anything it decrypts, for real secrets: create your own key with
age-keygen, keep it out of version control and encrypt your own files for it.
Steps¶
Declare the app once, with defaults for every pod.
PodDefaultsputs the KubernetesrestrictedPod Security settings and a read-only root filesystem on every container, and keeps API tokens out of pods that are not bound to a declared account:app = App( "reference", pod_defaults=PodDefaults( security=Security.restricted( user=10001, fs_group=10001, read_only_root_filesystem=True ), automount_token=False, # only pods bound to a declared account get a token termination_grace_seconds=10, ), )
Take the store password from a SOPS file.
Sops(...)names one value of an encrypted file; two templates derive the connection URL and the Redis configuration from it. The app only holds opaque references: the values are read at plan time into Piceli’s private store and written only into the Secret (see External sources):secrets = Secrets( store_password=Sops( "secrets/example.enc.yaml", "store.password", pass_env=["SOPS_AGE_KEY_FILE"] ), store_url=Template("redis://:{store_password}@store:6379/0"), store_conf=Template("dir /data\nappendonly yes\nrequirepass {store_password}\n"), ) # Secrets are never rewritten: a rotated value goes into a new name (-2). credentials = app.secret( "store-credentials-1", { "password": secrets.ref("store_password"), "url": secrets.ref("store_url"), "redis.conf": secrets.ref("store_conf"), }, )
The stateful store. A StatefulSet with a
ClaimTemplategets one PersistentVolumeClaim per pod (never pruned by a release) and a headless Service namedstore. Redis reads its configuration, password included, from the mounted Secret:store = app.stateful_set( "store", image=REDIS, command=["redis-server", "/etc/store/redis.conf"], ports=[6379], ready=app.probe.tcp(6379), live=app.probe.tcp(6379, initial_delay_seconds=10), env={"REDISCLI_AUTH": credentials.key("password")}, # for redis-cli checks volumes={ "/data": ClaimTemplate("data", size="64Mi"), "/etc/store": SecretVolume(credentials, items={"redis.conf": "redis.conf"}), }, resources=Resources(cpu="50m", memory="64Mi", memory_limit="128Mi"), )
Workers.
migrateis a Job that runs after the store is ready and before the api rolls out (app.depends);reportis a nightly CronJob:migrate = app.job( "migrate", image=REDIS, command=["redis-cli", "-h", "store", "SET", "schema-version", "1"], env={"REDISCLI_AUTH": credentials.key("password")}, backoff_limit=4, active_deadline_seconds=300, resources=Resources(cpu="10m", memory="16Mi"), ) app.depends(migrate, on=store) app.cron_job( "report", schedule="0 3 * * *", time_zone="Etc/UTC", concurrency="Forbid", image=REDIS, command=["redis-cli", "-h", "store", "INCR", "reports"], env={"REDISCLI_AUTH": credentials.key("password")}, backoff_limit=1, resources=Resources(cpu="10m", memory="16Mi"), )
The api and its permissions.
app.service_account(...)declares a ServiceAccount, a Role and a RoleBinding from typedRules; only the pods bound to it get a token:api_account = app.service_account( "api-reader", rules=[Rule(resources=["configmaps"], verbs=["get", "list", "watch"])], ) api = app.deployment( "api", image=BUSYBOX, command=["httpd", "-f", "-p", "8080", "-h", "/srv"], ports=[8080], ready=app.probe.http("/healthz", 8080), env={ "LOG_LEVEL": settings.key("LOG_LEVEL"), "STORE_URL": credentials.key("url"), }, volumes={"/srv": ConfigVolume(site)}, resources=Resources(cpu="20m", memory="16Mi", memory_limit="32Mi"), service_account=api_account, ) api_service = app.service(api, port=8080) app.depends(api, on=migrate)
The web front end. The autoscaler owns the replica count (
webdeclares noreplicas=), and the disruption budget keeps one pod up during node maintenance.access=tellspiceli statusandpiceli accesshow to reach it from a laptop:web = app.deployment( "web", image=BUSYBOX, command=["httpd", "-f", "-p", "8080", "-h", "/srv"], ports=[8080], ready=app.probe.http("/healthz", 8080), env={"API_URL": "http://api:8080"}, volumes={"/srv": ConfigVolume(site)}, resources=Resources(cpu="20m", memory="16Mi", memory_limit="32Mi"), ) web_service = app.service( web, port=80, target_port=8080, access=app.access.forward(local=18080, path="/"), # piceli access ) app.autoscaler(web, min_replicas=2, max_replicas=6, cpu=70) app.disruption_budget(web, max_unavailable=1) app.depends(web, on=api)
Traffic and TLS. An HTTPRoute attaches to a shared Gateway; an Ingress is declared too, in its own component, for local clusters without a Gateway controller. The Certificate’s spec is a model generated from the cert-manager CRD (
piceli codegen crd tests/fixtures/crds/cert-manager-certificate.yaml --out examples/reference/crds/certificate.py, see Custom resources and any other kind), so a typo or a wrong enum value fails here. One NetworkPolicy lets only this release’s pods reach its pods:app.http_route( "site", gateway=GatewayRef("public", namespace="gateways", section="https"), hosts=["dev.reference.example.com"], routes=[Route(web_service, "/"), Route(api_service, "/api")], ) # A local cluster without a Gateway controller gets an Ingress too (dev only). app.ingress( "site", hosts=["dev.reference.example.com"], routes=[Route(web_service, "/"), Route(api_service, "/api")], component="dev-ingress", ) app.resource( API_VERSION, KIND, "site-tls", CertificateSpec( secret_name="site-tls", dns_names=["dev.reference.example.com"], issuer_ref=IssuerRef(name="self-signed", kind="ClusterIssuer"), private_key=PrivateKey(algorithm="ECDSA", size=256), ), public=["spec.privateKey"], # algorithm settings, not key material ) # Only this release's pods may connect to its pods. app.network_policy( selector=app.release_selector, allow_from_selector=app.release_selector, name="internal", )
Environments name only what differs.
devlogs more and scales less;stagingandproduse their own hosts and issuers and leave out the Ingress;prodgets more replicas, bigger containers and wider autoscaler bounds (Scaling). Every key is checked against the declared objects when the environment is declared:def certificate(*hosts: str, issuer: str) -> CertificateSpec: return CertificateSpec( secret_name="site-tls", dns_names=list(hosts), issuer_ref=IssuerRef(name=issuer, kind="ClusterIssuer"), private_key=PrivateKey(algorithm="ECDSA", size=256), ) app.environment( "dev", namespace="reference-dev", config={"settings": {"LOG_LEVEL": "debug"}}, autoscalers={"web": Scaling(min_replicas=1, max_replicas=2)}, ) app.environment( "staging", namespace="reference-staging", hosts={"HTTPRoute/site": ["staging.reference.example.com"]}, specs={ "site-tls": certificate( "staging.reference.example.com", issuer="letsencrypt-staging" ) }, enabled={"dev-ingress": False}, ) app.environment( "prod", namespace="reference-prod", replicas={"api": 3}, autoscalers={"web": Scaling(min_replicas=3, max_replicas=10)}, resources={ "web": Resources(cpu="100m", memory="64Mi", memory_limit="128Mi"), "api": Resources(cpu="200m", memory="128Mi", memory_limit="256Mi"), }, config={"settings": {"LOG_LEVEL": "warning"}}, hosts={"HTTPRoute/site": ["reference.example.com", "www.reference.example.com"]}, specs={ "site-tls": certificate( "reference.example.com", "www.reference.example.com", issuer="letsencrypt" ) }, enabled={"dev-ingress": False}, )
One target per environment, secrets and checks. The pipeline deploys each environment to its own cluster and namespace, with its own state. The checks run after every deploy: the web page answers, and the store holds the schema version the Job wrote. A failed check rolls the release back:
pipeline = Pipeline( app, { # one target per environment; `--env` selects one (with its own state) "dev": Target.kubeconfig( os.environ.get("REFERENCE_KUBECONFIG", "reference.kubeconfig"), context=os.environ.get("REFERENCE_CONTEXT", "kind-reference"), namespace=os.environ.get("REFERENCE_NAMESPACE", "reference-dev"), ), "staging": Target.kubeconfig( "cluster.kubeconfig", context="main", namespace="reference-staging" ), "prod": Target.kubeconfig( "cluster.kubeconfig", context="main", namespace="reference-prod" ), }, secrets=secrets, checks=[ Checks.http(web_service, "/", expect=200, body_contains="reference app"), Checks.exec(store, ["redis-cli", "GET", "schema-version"], output_contains="1"), ], rollback_on_failed_checks=True, state_dir=os.environ.get("REFERENCE_STATE_DIR", ".piceli-deploy"), execution={"readiness_seconds": 300}, ) # `piceli status` and `piceli access` take a pipeline with one target. dev = pipeline.for_environment("dev")
Render and compare the environments (no cluster, no secret values):
piceli render examples/reference/app.py:app --env prod piceli render examples/reference/app.py:app --env staging --diff-env prod
Deploy
devto a disposable kind cluster. Thedevtarget readsREFERENCE_KUBECONFIG,REFERENCE_CONTEXTandREFERENCE_NAMESPACE(defaults:examples/reference/reference.kubeconfig,kind-reference,reference-dev); it never uses~/.kube/configor the current context:kind create cluster --name reference --kubeconfig examples/reference/reference.kubeconfig export KC="--kubeconfig examples/reference/reference.kubeconfig --context kind-reference" kubectl $KC apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.2.1/standard-install.yaml kubectl $KC apply --server-side -f tests/fixtures/crds/cert-manager-certificate.yaml kubectl $KC create namespace reference-dev export SOPS_AGE_KEY_FILE=$PWD/examples/reference/secrets/example-only.agekey piceli deploy examples/reference/app.py:pipeline --env dev --plan piceli deploy examples/reference/app.py:pipeline --env dev --approve <combined hash> piceli status examples/reference/app.py:dev piceli access examples/reference/app.py:dev # http://127.0.0.1:18080/
Change one value and deploy again. Raise
dev’sScaling(max_replicas=2)to3and plan: onlyHorizontalPodAutoscaler/webchanges. Deploy it, then roll back to the previous release:piceli release plan --spec examples/reference/app.py:pipeline --env dev piceli deploy examples/reference/app.py:pipeline --env dev --plan piceli deploy examples/reference/app.py:pipeline --env dev --approve <combined hash> piceli release rollback previous --spec examples/reference/app.py:pipeline --env dev piceli release rollback previous --spec examples/reference/app.py:pipeline --env dev --approve <plan hash>
Expected output¶
--diff-env prints only what differs between staging and prod: the override
values, then each changed object field by field. The namespace, which also
appears inside the RoleBinding’s subjects, is reported once and is not a
difference:
environments: staging (a) -> prod (b)
namespace: reference-staging -> reference-prod
values:
autoscalers.web: (absent) -> {"max_replicas": 10, "min_replicas": 3}
config.settings: (absent) -> {"LOG_LEVEL": "warning"}
hosts.HTTPRoute/site: ["staging.reference.example.com"] -> ["reference.example.com", "www.reference.example.com"]
…
~ HorizontalPodAutoscaler/web (component web):
spec.maxReplicas: 6 -> 10
spec.minReplicas: 2 -> 3
…
6 changed, 0 only in staging, 0 only in prod, 13 identical
The first dev deploy creates 20 objects, waits for the store, the Job and
the Deployments in dependency order, then runs the checks:
[plan] release reference-… (reapply): 20 create
[apply] reference-…: waiting for StatefulSet/store to be ready (1s)
[apply] reference-…: waiting for Job/migrate to be ready (1s)
[checks] reference-…: passed
deploy ready: release reference-…
If it fails¶
Symptom |
Meaning |
Fix |
|---|---|---|
|
|
Install |
|
|
Export |
|
The cert-manager or Gateway API CRDs are missing |
Install them (step 11). |
|
A check failed after the apply; the previous release was re-applied |
Read |
|
Targets never create namespaces |
|
What the example shows, and where to read more¶
In the example |
Page |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
Deploy an app from source, Reach your services from your laptop |
Limits worth knowing:
A
NetworkPolicyfromapp.network_policyadmits pods of the same namespace only; a Gateway or ingress controller in another namespace needs a policy the typed model does not declare yet.Pipeline(secrets=...)is shared by every environment: here all three read the same SOPS file. Per-environment files need one pipeline module per environment for now.busyboxserves static files as stand-ins for the web and api servers; replace the images and commands with your own.