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, and sops on PATH (to decrypt the store password; rendering does not need it).

  • To deploy dev: a disposable kind cluster, the Gateway API CRDs and the cert-manager Certificate CRD (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

  1. Declare the app once, with defaults for every pod. PodDefaults puts the Kubernetes restricted Pod 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,
        ),
    )
    
    
  2. 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"),
        },
    )
    
    
  3. The stateful store. A StatefulSet with a ClaimTemplate gets one PersistentVolumeClaim per pod (never pruned by a release) and a headless Service named store. 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"),
    )
    
    
  4. Workers. migrate is a Job that runs after the store is ready and before the api rolls out (app.depends); report is 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"),
    )
    
    
  5. The api and its permissions. app.service_account(...) declares a ServiceAccount, a Role and a RoleBinding from typed Rules; 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)
    
    
  6. The web front end. The autoscaler owns the replica count (web declares no replicas=), and the disruption budget keeps one pod up during node maintenance. access= tells piceli status and piceli access how 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)
    
    
  7. 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",
    )
    
    
    
  8. Environments name only what differs. dev logs more and scales less; staging and prod use their own hosts and issuers and leave out the Ingress; prod gets 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},
    )
    
    
  9. 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")
    
  10. 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
    
  11. Deploy dev to a disposable kind cluster. The dev target reads REFERENCE_KUBECONFIG, REFERENCE_CONTEXT and REFERENCE_NAMESPACE (defaults: examples/reference/reference.kubeconfig, kind-reference, reference-dev); it never uses ~/.kube/config or 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/
    
  12. Change one value and deploy again. Raise dev’s Scaling(max_replicas=2) to 3 and plan: only HorizontalPodAutoscaler/web changes. 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

secret-source-tool-missing

sops is not on PATH

Install sops.

secret-source-auth-failed

sops found no key for the file

Export SOPS_AGE_KEY_FILE as an absolute path (the pipeline passes only that variable to sops).

discovery-incomplete (cert-manager.io/v1/Certificate: api-unavailable)

The cert-manager or Gateway API CRDs are missing

Install them (step 11).

pipeline-checks-failed, rolled-back

A check failed after the apply; the previous release was re-applied

Read checks.results in the run and fix the app.

namespace-not-found

Targets never create namespaces

kubectl create namespace reference-dev with the same kubeconfig and context.

What the example shows, and where to read more

In the example

Page

App, PodDefaults, Security.restricted, workloads, Services, RBAC, network policies, autoscalers, disruption budgets, routes

Describe an app in typed Python

app.resource(...) with a spec generated by piceli codegen crd

Custom resources and any other kind

app.environment(...), Scaling, --env, --diff-env, one target per environment

Environments: one app for dev, staging and prod

Sops, Template, secrets that are never printed

Manage secrets: generate, template, import, fetch, rotate

Checks.http, Checks.exec, rollback on failed checks

Check a release and roll back automatically

piceli deploy, piceli release rollback, piceli status

Deploy an app from source, Reach your services from your laptop

Limits worth knowing:

  • A NetworkPolicy from app.network_policy admits 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.

  • busybox serves static files as stand-ins for the web and api servers; replace the images and commands with your own.