diff --git a/.ansible-lint b/.ansible-lint index 8a67ae127..75ec836ab 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -18,6 +18,8 @@ exclude_paths: - .patch_demo_export/ # Vendored BSOD recovery playbooks/roles (legacy naming; linted CaC is in openshift/setup.yml) - openshift/windows-bsod-recovery/ + # Vendored Helm chart -- Go templates and chart metadata, not Ansible YAML. + - infrastructure/openflake/chart/ mock_modules: - amazon.aws.aws_caller_info @@ -99,6 +101,7 @@ mock_modules: - community.windows.win_psmodule - containers.podman.podman_container - containers.podman.podman_image + - kubernetes.core.helm - kubernetes.core.k8s - kubernetes.core.k8s_cluster_info - kubernetes.core.k8s_info diff --git a/docs/_data/demos.yml b/docs/_data/demos.yml index b154dbeb8..b1d4a1706 100644 --- a/docs/_data/demos.yml +++ b/docs/_data/demos.yml @@ -1876,3 +1876,26 @@ playbooks: 1 url: /demos/infrastructure-mattermost/ github_path: infrastructure/setup.yml + +- slug: openflake + readme_path: infrastructure/docs/openflake.md + title: "Infrastructure | OpenFlake" + subtitle: "Run a ServiceNow-compatible ITSM backend on OpenShift for demos" + category: infrastructure + status: active + featured: false + tags: + - Playbook + - Survey + - OpenShift + - ITSM + - ServiceNow + - Helm + thumbnail: + gradient: "linear-gradient(135deg, #1f6feb 0%, #0b3d91 100%)" + icon: "🎫" + blurb: "Deploy OpenFlake — a lightweight ITSM platform with a ServiceNow-compatible REST API — on OpenShift via its bundled Helm chart, so servicenow.itsm content can run against it with only a URL change." + stats: + playbooks: 1 + url: /demos/openflake/ + github_path: infrastructure/openflake/provision.yml diff --git a/infrastructure/README.md b/infrastructure/README.md index c0c43e0fb..66868a1ab 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -58,6 +58,14 @@ Detect unauthorized changes to `/etc/ssh/sshd_config` via Linux audit, route eve | **Infrastructure | OPA - Deploy Open Policy Agent on OpenShift** | Deploys a demo (non-production) OPA on OpenShift, loads bundled Rego policies into a ConfigMap, and configures AAP's Policy as Code settings | | **Infrastructure | OPA - Add Policy** | Uploads a Rego policy to OPA via the REST API (in-memory only, does not persist across pod restarts) | +### OpenFlake (ITSM) + +#### Jobs + +| Job Template | Description | +|--------------|-------------| +| [**Infrastructure ǀ OpenFlake**](docs/openflake.md) | Installs or removes OpenFlake — a lightweight ITSM platform with a ServiceNow-compatible REST API — on OpenShift via its bundled Helm chart | + ## Post Setup After running `APD | Single demo setup` with `demo: infrastructure`: diff --git a/infrastructure/ao/tasks/wire_litemaas_integration.yml b/infrastructure/ao/tasks/wire_litemaas_integration.yml index d4a2c43f2..4c917394a 100644 --- a/infrastructure/ao/tasks/wire_litemaas_integration.yml +++ b/infrastructure/ao/tasks/wire_litemaas_integration.yml @@ -1,6 +1,6 @@ --- # Bridge Controller LiteMaaS into AO as LLM Provider credential + llm_provider -# integration (same pattern as intro-ao-workshop). Soft-skip when missing. +# integration. Soft-skip when missing. # # Secret source: Install JT must attach the Controller LiteMaaS credential so # LITELLM_* / OPENAI_* env injectors are present in this job. Non-secret fields diff --git a/infrastructure/docs/openflake.md b/infrastructure/docs/openflake.md new file mode 100644 index 000000000..f64b37453 --- /dev/null +++ b/infrastructure/docs/openflake.md @@ -0,0 +1,119 @@ +# OpenFlake — ITSM on OpenShift + +Deploy [OpenFlake](https://github.com/rlopez133/open-flake) — a lightweight ITSM platform with a ServiceNow-compatible REST API — on an OpenShift cluster. It gives demos a real incident/change backend to drive without needing a ServiceNow instance, and the ServiceNow-compatible endpoints mean `servicenow.itsm` content can point at it with only a URL change. + +This is **not** part of the automatic `infrastructure` demo setup. The job template is seeded by the demo setup, but the deployment only happens when someone launches it. + +## Prerequisites + +- OpenShift cluster with privileges to create projects, deployments, statefulsets, services, routes and PVCs +- A default StorageClass, or a StorageClass name to pass in (two PVCs are created: 10Gi for Postgres, 5Gi for attachments) +- OpenShift Credential configured in AAP (bearer token for cluster authentication) +- Product Demos EE, or another EE with `helm` on PATH — see [Helm binary](#helm-binary) + +## Configure credentials + +| Credential | Type | Where to get it | +|------------|------|-----------------| +| OpenShift Credential | OpenShift or Kubernetes API Bearer Token | OpenShift console — Service Account or user token | + +## Survey prompts + +| Prompt | Variable | Type | Required | Default | +|--------|----------|------|----------|---------| +| Operation | `openflake_operation` | multiplechoice (`install` / `uninstall`) | Yes | `install` | +| OpenFlake namespace | `openflake_namespace` | text | Yes | `openflake` | +| Route hostname | `openflake_route_host` | text | No | *(blank — OpenShift generates one)* | +| OpenFlake image tag | `openflake_image_tag` | text | Yes | `stable` | + +## Job templates + +| Template | Playbook | Description | +|----------|----------|-------------| +| Infrastructure ǀ OpenFlake | [`infrastructure/openflake/provision.yml`](../openflake/provision.yml) | Installs or removes OpenFlake via the bundled Helm chart | + +## What gets deployed + +| Component | Kind | Notes | +|-----------|------|-------| +| `openflake-backend` | Deployment | FastAPI app serving the ServiceNow-compatible REST API; Alembic migrations run on startup | +| `openflake-frontend` | Deployment | nginx serving the UI and proxying `/api` to the backend | +| `openflake-postgresql` | StatefulSet | Postgres 16 (`quay.io/sclorg/postgresql-16-c9s`) | +| `openflake` | Route | Edge TLS with HTTP redirect | +| `openflake` | Secret | Admin password, JWT signing key, Postgres password | + +## Credentials + +Leave the admin password unset (the default) and the chart generates one on first install, then reuses it on every subsequent run via a cluster lookup — re-running the template will not roll the password out from under a running demo. + +The job output prints the URL, username and password at the end of a successful install, so they can be copied straight out of the job. + +> [!NOTE] +> That is a deliberate choice for a demo workload: AAP retains job output and shows it to anyone with read access on the job. Fine for an ephemeral demo cluster, not something to carry into anything long-lived. Only the admin password is exposed — the same Secret also holds `SECRET_KEY` and `POSTGRESQL_PASSWORD`, and those stay out of the log. + +The password is also readable from the Secret at any time: + +```bash +oc -n openflake get secret openflake -o jsonpath="{.data.ADMIN_PASSWORD}" | base64 -d +``` + +Override with `openflake_admin_username` / `openflake_admin_password` in extra_vars if you need a fixed login. + +## Route hostname + +Leaving **Route hostname** blank is the normal path. The chart installs with `BASE_URL`/`CORS_ORIGINS` pointed at the in-cluster Service, the playbook then reads back the hostname OpenShift generated and runs a second Helm pass to correct them. Helm is idempotent, so later runs converge to a no-op. + +Supplying a hostname skips the second pass. + +## Helm binary + +`kubernetes.core.helm` shells out to the `helm` CLI. Product Demos EE already bakes it into `/usr/local/bin/helm` — see the `append_final` step in [`execution_environments/apd-ee-27.yml`](../../execution_environments/apd-ee-27.yml) (same in the `apd-ee-25` and `apd-ee-26` definitions). The template does not set an execution environment, so it runs on Product Demos EE as the organization default and helm is on PATH. + +Preflight fails with a clear message if it is not. To run on an EE that ships helm somewhere else: + +```yaml +openflake_helm_binary: /usr/bin/helm +``` + +Note the EE installs the `linux-amd64` build, so the job needs an amd64 execution node. + +## Uninstall + +Set **Operation** to `uninstall`. The playbook removes the Helm release, waits for the pods to finish terminating, then deletes the namespace — which takes the PVCs with it. **This destroys all OpenFlake data.** + +Before deleting anything it checks that the namespace actually holds resources labelled `app.kubernetes.io/part-of=openflake` for this release, and aborts if it does not. A mistyped namespace fails the job rather than deleting an unrelated project. The same check means uninstalling an already-removed release fails too — that is deliberate. + +To keep the namespace and only drop the release and its claims: + +```yaml +openflake_remove_namespace: false +openflake_remove_pvcs: true +``` + +## Extra variables + +Everything the survey does not expose is settable in extra_vars. + +| Variable | Default | Purpose | +|----------|---------|---------| +| `openflake_release_name` | `openflake` | Helm release name | +| `openflake_image_registry` | `quay.io/acme_corp` | Registry and org holding the images | +| `openflake_image_pull_policy` | `Always` | `stable` is a mutable tag, so `IfNotPresent` would reuse a stale layer | +| `openflake_route_enabled` | `true` | Set false for in-cluster-only access | +| `openflake_route_tls_enabled` | `true` | Edge TLS termination | +| `openflake_admin_username` | `admin` | Seed admin username | +| `openflake_admin_password` | *(generated)* | Pin the admin password instead of letting the chart generate it | +| `openflake_storage_class` | *(cluster default)* | StorageClass for both PVCs | +| `openflake_postgres_storage_size` | `10Gi` | Postgres volume | +| `openflake_attachments_storage_size` | `5Gi` | Attachments volume | +| `openflake_wait_timeout` | `10m` | Helm wait timeout | +| `openflake_verify` | `true` | Wait for Postgres, backend and frontend to report ready | +| `openflake_validate_certs` | *(from the credential's `K8S_AUTH_VERIFY_SSL`)* | Verify the cluster API certificate when helm connects | +| `openflake_ca_cert` | *(from the credential's `K8S_AUTH_SSL_CA_CERT`)* | Cluster CA for helm — a file path, or an inline PEM the playbook spills to a temp file | +| `openflake_helm_binary` | *(PATH lookup)* | Absolute path to helm on EEs that do not put it on PATH | + +## Known issues + +- The chart is vendored at [`infrastructure/openflake/chart`](../openflake/chart) rather than pulled from a chart repository, so it does not pick up upstream chart changes automatically. Update it in place when OpenFlake ships a new chart version. +- First boot can take several minutes: Alembic migrations run behind a Postgres advisory lock before the backend passes its startup probe. +- The deployment is not hardened for production — it is a demo backend. diff --git a/infrastructure/openflake/chart/.helmignore b/infrastructure/openflake/chart/.helmignore new file mode 100644 index 000000000..a85c8b1d9 --- /dev/null +++ b/infrastructure/openflake/chart/.helmignore @@ -0,0 +1,11 @@ +.DS_Store +.git/ +.gitignore +*.swp +*.bak +*.tmp +*.orig +*~ +.project +.idea/ +.vscode/ diff --git a/infrastructure/openflake/chart/Chart.yaml b/infrastructure/openflake/chart/Chart.yaml new file mode 100644 index 000000000..6b4987881 --- /dev/null +++ b/infrastructure/openflake/chart/Chart.yaml @@ -0,0 +1,24 @@ +apiVersion: v2 +name: openflake +description: Lightweight ITSM platform with a ServiceNow-compatible REST API, packaged for OpenShift +type: application + +# Chart version. Bump on any chart change. +version: 0.1.0 +# Version of OpenFlake this chart deploys by default. Overridden by image.tag. +appVersion: "0.1.0" + +keywords: + - itsm + - servicenow + - ansible + - openshift + - fastapi + +home: https://github.com/rlopez133/open-flake +sources: + - https://github.com/rlopez133/open-flake + +annotations: + charts.openshift.io/name: OpenFlake + charts.openshift.io/provider: OpenFlake diff --git a/infrastructure/openflake/chart/templates/NOTES.txt b/infrastructure/openflake/chart/templates/NOTES.txt new file mode 100644 index 000000000..0f441c6b4 --- /dev/null +++ b/infrastructure/openflake/chart/templates/NOTES.txt @@ -0,0 +1,55 @@ +OpenFlake {{ .Chart.AppVersion }} is installing into namespace {{ .Release.Namespace }}. + +Watch it come up: + + oc rollout status deploy/{{ include "openflake.backend.fullname" . }} -n {{ .Release.Namespace }} + oc rollout status deploy/{{ include "openflake.frontend.fullname" . }} -n {{ .Release.Namespace }} + +The backend applies Alembic migrations and seeds reference data during its +first boot, so that rollout can take a couple of minutes. + +{{ if .Values.route.enabled -}} +{{- if .Values.route.host -}} +URL: + + {{ include "openflake.publicUrl" . }} +{{- else -}} +ACTION REQUIRED -- route.host was not set. + +OpenShift generated a hostname for the Route, but the backend could not be +told about it at install time, so BASE_URL and CORS_ORIGINS currently point at +the in-cluster Service. Reference links and browser API clients will be wrong +until you feed the real hostname back in: + + ROUTE_HOST=$(oc get route {{ include "openflake.fullname" . }} -n {{ .Release.Namespace }} -o jsonpath='{.spec.host}') + helm upgrade {{ .Release.Name }} -n {{ .Release.Namespace }} --reuse-values --set route.host="$ROUTE_HOST" + +The Ansible role in ansible/roles/openflake_openshift does this automatically. +{{- end }} +{{- else -}} +No Route was created (route.enabled=false). Reach the UI with a port-forward: + + oc port-forward svc/{{ include "openflake.frontend.fullname" . }} 8080:{{ .Values.frontend.service.port }} -n {{ .Release.Namespace }} +{{- end }} + +Sign in as: + + username: {{ .Values.auth.adminUsername }} + password: oc get secret {{ include "openflake.secretName" . }} -n {{ .Release.Namespace }} -o jsonpath='{.data.ADMIN_PASSWORD}' | base64 -d + +{{ if not .Values.auth.adminPassword -}} +That password was generated at install time and is preserved across upgrades. +Change it after first login. +{{- end }} + +{{- if not .Values.backend.attachments.persistence.enabled }} + +WARNING: backend.attachments.persistence.enabled=false. Uploaded attachments +live in an emptyDir and are lost whenever the backend pod restarts. +{{- end }} +{{- if not .Values.postgresql.persistence.enabled }} + +WARNING: postgresql.persistence.enabled=false. The database lives in an +emptyDir and is lost whenever the Postgres pod restarts. Never do this outside +a throwaway demo. +{{- end }} diff --git a/infrastructure/openflake/chart/templates/_helpers.tpl b/infrastructure/openflake/chart/templates/_helpers.tpl new file mode 100644 index 000000000..ea063fa91 --- /dev/null +++ b/infrastructure/openflake/chart/templates/_helpers.tpl @@ -0,0 +1,202 @@ +{{/* +Chart name, overridable. +*/}} +{{- define "openflake.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Release-qualified base name for every resource this chart creates. +*/}} +{{- define "openflake.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{- define "openflake.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "openflake.backend.fullname" -}} +{{- printf "%s-backend" (include "openflake.fullname" .) | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "openflake.frontend.fullname" -}} +{{- printf "%s-frontend" (include "openflake.fullname" .) | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "openflake.postgresql.fullname" -}} +{{- printf "%s-postgresql" (include "openflake.fullname" .) | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Labels applied to every object. +*/}} +{{- define "openflake.labels" -}} +helm.sh/chart: {{ include "openflake.chart" . }} +app.kubernetes.io/name: {{ include "openflake.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +app.kubernetes.io/part-of: openflake +{{- with .Values.commonLabels }} +{{ toYaml . }} +{{- end }} +{{- end -}} + +{{/* +Selector labels for one component. Call as: + {{ include "openflake.selectorLabels" (dict "context" . "component" "backend") }} +*/}} +{{- define "openflake.selectorLabels" -}} +app.kubernetes.io/name: {{ include "openflake.name" .context }} +app.kubernetes.io/instance: {{ .context.Release.Name }} +app.kubernetes.io/component: {{ .component }} +{{- end -}} + +{{- define "openflake.serviceAccountName" -}} +{{- if .Values.serviceAccount.create -}} +{{- default (include "openflake.fullname" .) .Values.serviceAccount.name -}} +{{- else -}} +{{- default "default" .Values.serviceAccount.name -}} +{{- end -}} +{{- end -}} + +{{/* +Name of the Secret holding application credentials. +*/}} +{{- define "openflake.secretName" -}} +{{- if .Values.auth.existingSecret -}} +{{- .Values.auth.existingSecret -}} +{{- else -}} +{{- include "openflake.fullname" . -}} +{{- end -}} +{{- end -}} + +{{- define "openflake.backend.image" -}} +{{- $tag := default .Values.image.tag .Values.backend.image.tag -}} +{{- printf "%s/%s:%s" .Values.image.registry .Values.backend.image.repository $tag -}} +{{- end -}} + +{{- define "openflake.frontend.image" -}} +{{- $tag := default .Values.image.tag .Values.frontend.image.tag -}} +{{- printf "%s/%s:%s" .Values.image.registry .Values.frontend.image.repository $tag -}} +{{- end -}} + +{{/* +Data of the chart-managed Secret as it already exists in the cluster, as JSON. +Lets `helm upgrade` reuse previously generated credentials instead of rolling +them. Returns "{}" on first install and during `helm template`, where the +cluster is not consulted. +*/}} +{{- define "openflake.existingSecretData" -}} +{{- $found := lookup "v1" "Secret" .Release.Namespace (include "openflake.secretName" .) -}} +{{- if and $found $found.data -}} +{{- toJson $found.data -}} +{{- else -}} +{{- "{}" -}} +{{- end -}} +{{- end -}} + +{{/* +Credential resolution order: explicit value, then the value already stored in +the cluster, then a freshly generated one. + +Each of these calls randAlphaNum, so a single render must resolve each value +exactly once and reuse it through a variable. Only templates/secret.yaml calls +them; every workload reads the resulting Secret. +*/}} +{{- define "openflake.postgresPassword" -}} +{{- if .Values.postgresql.password -}} +{{- .Values.postgresql.password -}} +{{- else -}} +{{- $data := fromJson (include "openflake.existingSecretData" .) -}} +{{- if $data.POSTGRESQL_PASSWORD -}} +{{- b64dec $data.POSTGRESQL_PASSWORD -}} +{{- else -}} +{{- randAlphaNum 24 -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{- define "openflake.secretKey" -}} +{{- if .Values.auth.secretKey -}} +{{- .Values.auth.secretKey -}} +{{- else -}} +{{- $data := fromJson (include "openflake.existingSecretData" .) -}} +{{- if $data.SECRET_KEY -}} +{{- b64dec $data.SECRET_KEY -}} +{{- else -}} +{{- randAlphaNum 48 -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{- define "openflake.adminPassword" -}} +{{- if .Values.auth.adminPassword -}} +{{- .Values.auth.adminPassword -}} +{{- else -}} +{{- $data := fromJson (include "openflake.existingSecretData" .) -}} +{{- if $data.ADMIN_PASSWORD -}} +{{- b64dec $data.ADMIN_PASSWORD -}} +{{- else -}} +{{- randAlphaNum 20 -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +In-cluster DNS name of the backend Service. nginx resolves `set`-assigned +upstreams through its `resolver` directive, which ignores the search domains +in /etc/resolv.conf, so the frontend needs the fully qualified name. +*/}} +{{- define "openflake.backend.serviceFqdn" -}} +{{- printf "%s.%s.svc.cluster.local" (include "openflake.backend.fullname" .) .Release.Namespace -}} +{{- end -}} + +{{/* +Public URL users reach OpenFlake on. Derived from the Route unless overridden. +Empty when route.host was not supplied and no explicit baseUrl was given. +*/}} +{{- define "openflake.publicUrl" -}} +{{- if .Values.config.baseUrl -}} +{{- .Values.config.baseUrl | trimSuffix "/" -}} +{{- else if and .Values.route.enabled .Values.route.host -}} +{{- $scheme := ternary "https" "http" .Values.route.tls.enabled -}} +{{- printf "%s://%s" $scheme .Values.route.host -}} +{{- end -}} +{{- end -}} + +{{/* +BASE_URL for the backend. Falls back to the in-cluster frontend Service when +the public hostname is not known yet, so generated links stay resolvable from +inside the cluster. NOTES.txt tells the installer how to correct this. +*/}} +{{- define "openflake.baseUrl" -}} +{{- $public := include "openflake.publicUrl" . -}} +{{- if $public -}} +{{- $public -}} +{{- else -}} +{{- printf "http://%s.%s.svc.cluster.local:%v" (include "openflake.frontend.fullname" .) .Release.Namespace .Values.frontend.service.port -}} +{{- end -}} +{{- end -}} + +{{/* +CORS origins for API clients calling from a browser. The UI itself is served +same-origin through nginx and does not need an entry here. +*/}} +{{- define "openflake.corsOrigins" -}} +{{- if .Values.config.corsOrigins -}} +{{- .Values.config.corsOrigins -}} +{{- else -}} +{{- include "openflake.baseUrl" . -}} +{{- end -}} +{{- end -}} diff --git a/infrastructure/openflake/chart/templates/backend.yaml b/infrastructure/openflake/chart/templates/backend.yaml new file mode 100644 index 000000000..1ddc05ad4 --- /dev/null +++ b/infrastructure/openflake/chart/templates/backend.yaml @@ -0,0 +1,161 @@ +{{- if and .Values.backend.attachments.persistence.enabled (not .Values.backend.attachments.persistence.existingClaim) }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: {{ include "openflake.backend.fullname" . }}-attachments + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: backend + annotations: + # Uploaded attachments outlive the release; deleting the chart should not + # silently discard them. + helm.sh/resource-policy: keep + {{- with .Values.commonAnnotations }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + accessModes: + - {{ .Values.backend.attachments.persistence.accessMode }} + resources: + requests: + storage: {{ .Values.backend.attachments.persistence.size | quote }} + {{- if .Values.backend.attachments.persistence.storageClass }} + storageClassName: {{ .Values.backend.attachments.persistence.storageClass | quote }} + {{- end }} +--- +{{- end }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "openflake.backend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: backend + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + ports: + - name: http + port: {{ .Values.backend.service.port }} + targetPort: http + protocol: TCP + selector: + {{- include "openflake.selectorLabels" (dict "context" . "component" "backend") | nindent 4 }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "openflake.backend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: backend + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + replicas: {{ .Values.backend.replicas }} + {{- if and .Values.backend.attachments.persistence.enabled (eq .Values.backend.attachments.persistence.accessMode "ReadWriteOnce") }} + # A ReadWriteOnce attachments volume cannot be attached to an old and a new + # pod at once, so a rolling update would deadlock. + strategy: + type: Recreate + {{- end }} + selector: + matchLabels: + {{- include "openflake.selectorLabels" (dict "context" . "component" "backend") | nindent 6 }} + template: + metadata: + labels: + {{- include "openflake.labels" . | nindent 8 }} + app.kubernetes.io/component: backend + spec: + serviceAccountName: {{ include "openflake.serviceAccountName" . }} + {{- with .Values.image.pullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: backend + image: {{ include "openflake.backend.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + ports: + - name: http + containerPort: 8000 + protocol: TCP + envFrom: + # Supplies DATABASE_URL, SECRET_KEY, ADMIN_USERNAME, ADMIN_PASSWORD. + - secretRef: + name: {{ include "openflake.secretName" . }} + env: + - name: BASE_URL + value: {{ include "openflake.baseUrl" . | quote }} + - name: CORS_ORIGINS + value: {{ include "openflake.corsOrigins" . | quote }} + - name: TRUSTED_PROXIES + value: {{ .Values.config.trustedProxies | quote }} + - name: LOG_LEVEL + value: {{ .Values.config.logLevel | quote }} + - name: ATTACHMENTS_PATH + value: /data/attachments + {{- with .Values.backend.extraEnv }} + {{- toYaml . | nindent 12 }} + {{- end }} + # Alembic migrations and first-boot seeding run inside the app's + # lifespan, before uvicorn starts serving, so /health/live only + # answers once that finished. The startup probe covers that window. + startupProbe: + httpGet: + path: /health/live + port: http + failureThreshold: {{ .Values.backend.startupProbe.failureThreshold }} + periodSeconds: {{ .Values.backend.startupProbe.periodSeconds }} + livenessProbe: + httpGet: + path: /health/live + port: http + initialDelaySeconds: {{ .Values.backend.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.backend.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.backend.livenessProbe.timeoutSeconds }} + readinessProbe: + httpGet: + path: /health/ready + port: http + initialDelaySeconds: {{ .Values.backend.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.backend.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.backend.readinessProbe.timeoutSeconds }} + resources: + {{- toYaml .Values.backend.resources | nindent 12 }} + volumeMounts: + - name: attachments + mountPath: /data/attachments + {{- with .Values.backend.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.backend.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.backend.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + volumes: + - name: attachments + {{- if .Values.backend.attachments.persistence.enabled }} + persistentVolumeClaim: + claimName: {{ default (printf "%s-attachments" (include "openflake.backend.fullname" .)) .Values.backend.attachments.persistence.existingClaim }} + {{- else }} + emptyDir: {} + {{- end }} diff --git a/infrastructure/openflake/chart/templates/frontend.yaml b/infrastructure/openflake/chart/templates/frontend.yaml new file mode 100644 index 000000000..2944642a1 --- /dev/null +++ b/infrastructure/openflake/chart/templates/frontend.yaml @@ -0,0 +1,101 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "openflake.frontend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: frontend + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + ports: + - name: http + port: {{ .Values.frontend.service.port }} + targetPort: http + protocol: TCP + selector: + {{- include "openflake.selectorLabels" (dict "context" . "component" "frontend") | nindent 4 }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "openflake.frontend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: frontend + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + replicas: {{ .Values.frontend.replicas }} + selector: + matchLabels: + {{- include "openflake.selectorLabels" (dict "context" . "component" "frontend") | nindent 6 }} + template: + metadata: + labels: + {{- include "openflake.labels" . | nindent 8 }} + app.kubernetes.io/component: frontend + spec: + serviceAccountName: {{ include "openflake.serviceAccountName" . }} + {{- with .Values.image.pullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: frontend + image: {{ include "openflake.frontend.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + ports: + - name: http + containerPort: 8080 + protocol: TCP + env: + # nginx proxies /api, /oauth_token.do and /health to the backend. + # It needs the fully qualified Service name -- see the comment on + # openflake.backend.serviceFqdn in _helpers.tpl. + - name: OPENFLAKE_BACKEND_HOST + value: {{ include "openflake.backend.serviceFqdn" . | quote }} + - name: OPENFLAKE_BACKEND_PORT + value: {{ .Values.backend.service.port | quote }} + {{- with .Values.frontend.extraEnv }} + {{- toYaml . | nindent 12 }} + {{- end }} + livenessProbe: + httpGet: + path: / + port: http + initialDelaySeconds: 10 + periodSeconds: 20 + timeoutSeconds: 5 + readinessProbe: + httpGet: + path: / + port: http + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + resources: + {{- toYaml .Values.frontend.resources | nindent 12 }} + {{- with .Values.frontend.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.frontend.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.frontend.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/infrastructure/openflake/chart/templates/postgresql.yaml b/infrastructure/openflake/chart/templates/postgresql.yaml new file mode 100644 index 000000000..c00fb0a2c --- /dev/null +++ b/infrastructure/openflake/chart/templates/postgresql.yaml @@ -0,0 +1,137 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "openflake.postgresql.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + ports: + - name: postgresql + port: {{ .Values.postgresql.service.port }} + targetPort: postgresql + protocol: TCP + selector: + {{- include "openflake.selectorLabels" (dict "context" . "component" "postgresql") | nindent 4 }} +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "openflake.postgresql.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + replicas: 1 + serviceName: {{ include "openflake.postgresql.fullname" . }} + selector: + matchLabels: + {{- include "openflake.selectorLabels" (dict "context" . "component" "postgresql") | nindent 6 }} + template: + metadata: + labels: + {{- include "openflake.labels" . | nindent 8 }} + app.kubernetes.io/component: postgresql + spec: + serviceAccountName: {{ include "openflake.serviceAccountName" . }} + {{- with .Values.image.pullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: postgresql + image: {{ .Values.postgresql.image | quote }} + imagePullPolicy: {{ .Values.postgresql.imagePullPolicy }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + ports: + - name: postgresql + containerPort: 5432 + protocol: TCP + env: + - name: POSTGRESQL_USER + valueFrom: + secretKeyRef: + name: {{ include "openflake.secretName" . }} + key: POSTGRESQL_USER + - name: POSTGRESQL_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "openflake.secretName" . }} + key: POSTGRESQL_PASSWORD + - name: POSTGRESQL_DATABASE + valueFrom: + secretKeyRef: + name: {{ include "openflake.secretName" . }} + key: POSTGRESQL_DATABASE + # Probes shipped inside the sclorg image: they run pg_isready against + # the local socket, so they work regardless of the generated password. + readinessProbe: + exec: + command: + - /usr/libexec/check-container + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + livenessProbe: + exec: + command: + - /usr/libexec/check-container + - --live + initialDelaySeconds: 120 + periodSeconds: 20 + timeoutSeconds: 10 + failureThreshold: 3 + resources: + {{- toYaml .Values.postgresql.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: /var/lib/pgsql/data + {{- with .Values.postgresql.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.postgresql.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.postgresql.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- if not .Values.postgresql.persistence.enabled }} + volumes: + - name: data + emptyDir: {} + {{- end }} + {{- if .Values.postgresql.persistence.enabled }} + volumeClaimTemplates: + - metadata: + name: data + labels: + {{- include "openflake.labels" . | nindent 10 }} + app.kubernetes.io/component: postgresql + spec: + accessModes: + - {{ .Values.postgresql.persistence.accessMode }} + resources: + requests: + storage: {{ .Values.postgresql.persistence.size | quote }} + {{- if .Values.postgresql.persistence.storageClass }} + storageClassName: {{ .Values.postgresql.persistence.storageClass | quote }} + {{- end }} + {{- end }} diff --git a/infrastructure/openflake/chart/templates/route.yaml b/infrastructure/openflake/chart/templates/route.yaml new file mode 100644 index 000000000..bb9dbf78a --- /dev/null +++ b/infrastructure/openflake/chart/templates/route.yaml @@ -0,0 +1,32 @@ +{{- if .Values.route.enabled }} +apiVersion: route.openshift.io/v1 +kind: Route +metadata: + name: {{ include "openflake.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: frontend + {{- with (merge (dict) .Values.route.annotations .Values.commonAnnotations) }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- with .Values.route.host }} + host: {{ . | quote }} + {{- end }} + to: + kind: Service + name: {{ include "openflake.frontend.fullname" . }} + weight: 100 + port: + targetPort: http + {{- if .Values.route.tls.enabled }} + # Edge termination: the router holds the certificate and forwards plain HTTP + # to nginx, which is why the pods do not need OPENFLAKE_SSL_* configured. + tls: + termination: {{ .Values.route.tls.termination }} + insecureEdgeTerminationPolicy: {{ .Values.route.tls.insecureEdgeTerminationPolicy }} + {{- end }} + wildcardPolicy: None +{{- end }} diff --git a/infrastructure/openflake/chart/templates/secret.yaml b/infrastructure/openflake/chart/templates/secret.yaml new file mode 100644 index 000000000..1903ec870 --- /dev/null +++ b/infrastructure/openflake/chart/templates/secret.yaml @@ -0,0 +1,35 @@ +{{- if not .Values.auth.existingSecret }} +{{/* +Resolve each generated credential exactly once per render and reuse it through +a variable. Calling the helpers twice would produce two different random +values -- the DATABASE_URL below embeds the same password stored in +POSTGRESQL_PASSWORD, and Postgres reads the latter to create the account. +*/}} +{{- $pgPassword := include "openflake.postgresPassword" . -}} +{{- $databaseUrl := printf "postgresql+asyncpg://%s:%s@%s:%v/%s" + .Values.postgresql.username + $pgPassword + (include "openflake.postgresql.fullname" .) + .Values.postgresql.service.port + .Values.postgresql.database -}} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "openflake.secretName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + {{- with .Values.commonAnnotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +type: Opaque +stringData: + DATABASE_URL: {{ $databaseUrl | quote }} + SECRET_KEY: {{ include "openflake.secretKey" . | quote }} + ADMIN_USERNAME: {{ .Values.auth.adminUsername | quote }} + ADMIN_PASSWORD: {{ include "openflake.adminPassword" . | quote }} + POSTGRESQL_USER: {{ .Values.postgresql.username | quote }} + POSTGRESQL_PASSWORD: {{ $pgPassword | quote }} + POSTGRESQL_DATABASE: {{ .Values.postgresql.database | quote }} +{{- end }} diff --git a/infrastructure/openflake/chart/templates/serviceaccount.yaml b/infrastructure/openflake/chart/templates/serviceaccount.yaml new file mode 100644 index 000000000..40c6e59d2 --- /dev/null +++ b/infrastructure/openflake/chart/templates/serviceaccount.yaml @@ -0,0 +1,13 @@ +{{- if .Values.serviceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "openflake.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + {{- with (merge (dict) .Values.serviceAccount.annotations .Values.commonAnnotations) }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/infrastructure/openflake/chart/templates/tests/test-api-ready.yaml b/infrastructure/openflake/chart/templates/tests/test-api-ready.yaml new file mode 100644 index 000000000..d8cd2d4e8 --- /dev/null +++ b/infrastructure/openflake/chart/templates/tests/test-api-ready.yaml @@ -0,0 +1,41 @@ +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "openflake.fullname" . }}-test-api-ready + namespace: {{ .Release.Namespace }} + labels: + {{- include "openflake.labels" . | nindent 4 }} + app.kubernetes.io/component: test + annotations: + helm.sh/hook: test + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +spec: + restartPolicy: Never + {{- with .Values.image.pullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 4 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 4 }} + containers: + - name: test + image: {{ include "openflake.backend.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + securityContext: + {{- toYaml .Values.securityContext | nindent 8 }} + command: + - python + - -c + - | + import json + import sys + import urllib.request + + # Through nginx, which also proves the frontend's proxy to the + # backend Service resolves. + url = "http://{{ include "openflake.frontend.fullname" . }}:{{ .Values.frontend.service.port }}/health/ready" + with urllib.request.urlopen(url, timeout=15) as response: + body = json.load(response) + print(f"{url} -> {response.status} {body}") + if body.get("status") != "ready": + sys.exit(1) diff --git a/infrastructure/openflake/chart/values.yaml b/infrastructure/openflake/chart/values.yaml new file mode 100644 index 000000000..91cae559b --- /dev/null +++ b/infrastructure/openflake/chart/values.yaml @@ -0,0 +1,180 @@ +# Default values for the OpenFlake OpenShift chart. +# +# Minimal install: +# helm install openflake deploy/helm/openflake \ +# -n openflake --create-namespace \ +# --set route.host=openflake.apps.example.com +# +# Leaving route.host empty is supported: OpenShift generates a hostname, and +# the chart's NOTES output tells you how to feed it back in so that baseUrl +# and CORS match the real URL. + +# -- Override the chart name used in resource names. +nameOverride: "" +# -- Override the full release-qualified name used in resource names. +fullnameOverride: "" + +image: + # -- Registry and organization holding the OpenFlake images. + registry: quay.io/acme_corp + # -- Tag applied to both images unless overridden per component. + tag: stable + # stable is a mutable tag, so IfNotPresent would reuse a stale cached layer. + pullPolicy: Always + # -- Names of image pull secrets, e.g. [{name: my-quay-secret}]. + pullSecrets: [] + +serviceAccount: + # -- Create a ServiceAccount for the workloads. + create: true + # -- Use an existing ServiceAccount instead of creating one. + name: "" + annotations: {} + +# Application settings rendered into the backend's environment. +config: + # -- Public base URL used in reference links. Derived from route.host when empty. + baseUrl: "" + # -- Comma-separated CORS origins. Derived from route.host when empty. + corsOrigins: "" + # -- Trusted reverse proxies for X-Forwarded-* headers. "*" trusts the OpenShift router. + trustedProxies: "*" + # -- Backend log level. + logLevel: INFO + +auth: + # -- Seed admin username. + adminUsername: admin + # -- Seed admin password. Generated and persisted across upgrades when empty. + adminPassword: "" + # -- JWT signing key. Generated and persisted across upgrades when empty. + secretKey: "" + # -- Use a pre-created Secret instead of the chart-managed one. It must + # supply DATABASE_URL, SECRET_KEY, ADMIN_USERNAME, ADMIN_PASSWORD and + # POSTGRESQL_PASSWORD. + existingSecret: "" + +backend: + replicas: 1 + image: + repository: openflake-backend + # -- Overrides image.tag for the backend only. + tag: "" + service: + port: 8000 + resources: + requests: + cpu: 100m + memory: 512Mi + limits: + memory: 1Gi + # Alembic migrations run on startup behind a Postgres advisory lock, so the + # first boot can take a while. The startup probe covers that window before + # the liveness probe starts counting. + startupProbe: + failureThreshold: 60 + periodSeconds: 5 + livenessProbe: + initialDelaySeconds: 0 + periodSeconds: 20 + timeoutSeconds: 5 + readinessProbe: + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + nodeSelector: {} + tolerations: [] + affinity: {} + # -- Extra environment variables, e.g. [{name: FOO, value: bar}]. + extraEnv: [] + + attachments: + persistence: + # -- Persist uploaded attachments on a PVC. Strongly recommended. + enabled: true + size: 5Gi + # -- StorageClass name. Empty uses the cluster default. + storageClass: "" + # -- ReadWriteOnce pins the backend to one replica. Use ReadWriteMany to scale out. + accessMode: ReadWriteOnce + # -- Mount an existing PVC instead of creating one. + existingClaim: "" + +frontend: + replicas: 1 + image: + repository: openflake-frontend + # -- Overrides image.tag for the frontend only. + tag: "" + service: + port: 8080 + resources: + requests: + cpu: 50m + memory: 128Mi + limits: + memory: 256Mi + nodeSelector: {} + tolerations: [] + affinity: {} + extraEnv: [] + +postgresql: + # -- Postgres 16 built for OpenShift: runs under an arbitrary UID with GID 0. + image: quay.io/sclorg/postgresql-16-c9s:latest + imagePullPolicy: IfNotPresent + database: openflake + username: openflake + # -- Database password. Generated and persisted across upgrades when empty. + # Keep it alphanumeric: it is embedded verbatim in the DATABASE_URL. + password: "" + service: + port: 5432 + persistence: + enabled: true + size: 10Gi + # -- StorageClass name. Empty uses the cluster default. + storageClass: "" + accessMode: ReadWriteOnce + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + memory: 1Gi + nodeSelector: {} + tolerations: [] + affinity: {} + +route: + # -- Expose the UI and API through an OpenShift Route. + enabled: true + # -- Hostname for the Route. Empty lets OpenShift generate one. + host: "" + annotations: {} + tls: + # -- Terminate TLS at the router. The pods themselves stay on plain HTTP. + enabled: true + termination: edge + insecureEdgeTerminationPolicy: Redirect + +# Pod- and container-level security settings. +# +# The defaults deliberately omit runAsUser so that OpenShift's restricted-v2 +# SCC can inject a per-namespace UID. On vanilla Kubernetes, which has no SCC +# to do that, set podSecurityContext.runAsUser to any non-zero value. +podSecurityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + +securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + +# -- Labels added to every resource the chart creates. +commonLabels: {} +# -- Annotations added to every resource the chart creates. +commonAnnotations: {} diff --git a/infrastructure/openflake/provision.yml b/infrastructure/openflake/provision.yml new file mode 100644 index 000000000..aa96f7cd1 --- /dev/null +++ b/infrastructure/openflake/provision.yml @@ -0,0 +1,118 @@ +--- +# The operation comes from a survey rather than a provision/destroy flag, and +# the generated admin password is read back out of the Secret the chart +# creates rather than cached on the execution node. +- name: OpenFlake | Provision on OpenShift + hosts: localhost + connection: local + gather_facts: false + + vars: + _openflake_operation: '{{ openflake_operation | default("install") }}' + _openflake_namespace: '{{ openflake_namespace | default("openflake") }}' + _openflake_release_name: '{{ openflake_release_name | default("openflake") }}' + + # Vendored next to this playbook so the Ansible Product Demos project + # ships the chart it installs. + _openflake_chart_path: '{{ playbook_dir }}/chart' + + _openflake_image_registry: '{{ openflake_image_registry | default("quay.io/acme_corp") }}' + _openflake_image_tag: '{{ openflake_image_tag | default("stable") }}' + # The tag is mutable, so IfNotPresent would reuse a stale cached layer. + _openflake_image_pull_policy: '{{ openflake_image_pull_policy | default("Always") }}' + + # Empty lets OpenShift generate a hostname, which this playbook then + # reconciles into BASE_URL/CORS_ORIGINS with a second Helm pass. + _openflake_route_host: '{{ openflake_route_host | default("") }}' + _openflake_route_enabled: '{{ openflake_route_enabled | default(true) | bool }}' + _openflake_route_tls_enabled: '{{ openflake_route_tls_enabled | default(true) | bool }}' + + _openflake_admin_username: '{{ openflake_admin_username | default("admin") }}' + # Left empty, the chart generates the admin password, the JWT key and the + # Postgres password, and preserves them across upgrades via a cluster + # lookup. The install task reads the admin password back afterwards. + _openflake_admin_password: '{{ openflake_admin_password | default("") }}' + + _openflake_postgres_storage_size: '{{ openflake_postgres_storage_size | default("10Gi") }}' + _openflake_attachments_storage_size: '{{ openflake_attachments_storage_size | default("5Gi") }}' + _openflake_storage_class: '{{ openflake_storage_class | default("") }}' + + _openflake_wait: '{{ openflake_wait | default(true) | bool }}' + _openflake_wait_timeout: '{{ openflake_wait_timeout | default("10m") }}' + _openflake_verify: '{{ openflake_verify | default(true) | bool }}' + _openflake_verify_retries: '{{ openflake_verify_retries | default(30) | int }}' + _openflake_verify_delay: '{{ openflake_verify_delay | default(10) | int }}' + + _openflake_remove_pvcs: '{{ openflake_remove_pvcs | default(true) | bool }}' + _openflake_remove_namespace: '{{ openflake_remove_namespace | default(true) | bool }}' + _openflake_namespace_delete_timeout: '{{ openflake_namespace_delete_timeout | default(600) | int }}' + + # kubernetes.core.helm shells out to the helm CLI, which does not read the + # K8S_AUTH_* env vars the OpenShift credential injects. Pass them through + # explicitly so helm talks to the same cluster the k8s modules do. + _openflake_api_url: '{{ lookup("env", "K8S_AUTH_HOST") | default("", true) }}' + _openflake_api_key: '{{ lookup("env", "K8S_AUTH_API_KEY") | default("", true) }}' + + # Take the TLS posture from the credential rather than hardcoding it, so + # helm agrees with the k8s modules in this same play -- they read these + # env vars themselves, helm does not. + _openflake_validate_certs: >- + {{ openflake_validate_certs + | default(lookup("env", "K8S_AUTH_VERIFY_SSL") | default("true", true), true) | bool }} + _openflake_ca_raw: >- + {{ openflake_ca_cert + | default(lookup("env", "K8S_AUTH_SSL_CA_CERT") | default("", true), true) }} + _openflake_ca_is_inline: '{{ _openflake_ca_raw is search("BEGIN CERTIFICATE") }}' + # preflight.yml overrides this with a path once it has resolved the CA. + _openflake_ca_cert: '' + + # Product Demos EE bakes helm into /usr/local/bin + # (execution_environments/apd-ee-27.yml), so this only needs setting when + # the job runs on an EE that does not ship it. + _openflake_helm_binary: '{{ openflake_helm_binary | default("") }}' + + tasks: + - name: Reject an unknown operation + ansible.builtin.assert: + that: + - _openflake_operation in ["install", "uninstall"] + fail_msg: >- + openflake_operation must be 'install' or 'uninstall', + got '{{ _openflake_operation }}'. + quiet: true + + # Both come from free-text survey fields and the uninstall path deletes + # the namespace, so reject anything that is not a well-formed name before + # it reaches a destructive task. + - name: Validate the namespace and release name + ansible.builtin.assert: + that: + - _openflake_namespace is match('^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$') + - _openflake_release_name is match('^[a-z0-9]([-a-z0-9]{0,51}[a-z0-9])?$') + fail_msg: >- + openflake_namespace ('{{ _openflake_namespace }}') and + openflake_release_name ('{{ _openflake_release_name }}') must be + lowercase RFC 1123 labels. + quiet: true + + - name: Verify the OpenShift credential env vars are set + ansible.builtin.assert: + that: + - _openflake_api_url | length > 0 + - _openflake_api_key | length > 0 + fail_msg: >- + K8S_AUTH_HOST and K8S_AUTH_API_KEY must be set. Attach an + 'OpenShift or Kubernetes API Bearer Token' credential to this + job template. + quiet: true + + - name: Run preflight checks + ansible.builtin.include_tasks: tasks/preflight.yml + + - name: Install OpenFlake + ansible.builtin.include_tasks: tasks/install.yml + when: _openflake_operation == "install" + + - name: Uninstall OpenFlake + ansible.builtin.include_tasks: tasks/uninstall.yml + when: _openflake_operation == "uninstall" diff --git a/infrastructure/openflake/tasks/install.yml b/infrastructure/openflake/tasks/install.yml new file mode 100644 index 000000000..6d41e5a1a --- /dev/null +++ b/infrastructure/openflake/tasks/install.yml @@ -0,0 +1,187 @@ +--- +- name: Assemble the base Helm values + ansible.builtin.set_fact: + _openflake_release_values: + image: + registry: '{{ _openflake_image_registry }}' + tag: '{{ _openflake_image_tag }}' + pullPolicy: '{{ _openflake_image_pull_policy }}' + auth: + adminUsername: '{{ _openflake_admin_username }}' + route: + enabled: '{{ _openflake_route_enabled | bool }}' + tls: + enabled: '{{ _openflake_route_tls_enabled | bool }}' + postgresql: + persistence: + size: '{{ _openflake_postgres_storage_size }}' + backend: + attachments: + persistence: + size: '{{ _openflake_attachments_storage_size }}' + +- name: Layer in the optional settings that were supplied + ansible.builtin.set_fact: + _openflake_release_values: >- + {{ + _openflake_release_values + | combine({'route': {'host': _openflake_route_host}} + if _openflake_route_host else {}, recursive=True) + | combine({'postgresql': {'persistence': {'storageClass': _openflake_storage_class}}, + 'backend': {'attachments': {'persistence': {'storageClass': _openflake_storage_class}}}} + if _openflake_storage_class else {}, recursive=True) + }} + +# Merged separately so the credentials can be hidden from the job output +# without also hiding the settings above. Left empty, the chart generates the +# admin password, JWT key and Postgres password on first install and reuses +# them on every upgrade via a cluster lookup. +- name: Merge an explicitly supplied admin password + ansible.builtin.set_fact: + _openflake_release_values: >- + {{ + _openflake_release_values + | combine({'auth': {'adminPassword': _openflake_admin_password}} + if _openflake_admin_password else {}, recursive=True) + }} + no_log: true + +- name: Install or upgrade the OpenFlake release + kubernetes.core.helm: + release_name: '{{ _openflake_release_name }}' + release_namespace: '{{ _openflake_namespace }}' + chart_ref: '{{ _openflake_chart_path }}' + create_namespace: true + release_values: '{{ _openflake_release_values }}' + binary_path: '{{ _openflake_helm_binary | default(omit, true) }}' + host: '{{ _openflake_api_url }}' + api_key: '{{ _openflake_api_key }}' + validate_certs: '{{ _openflake_validate_certs | bool }}' + ca_cert: '{{ _openflake_ca_cert | default(omit, true) }}' + wait: '{{ _openflake_wait | bool }}' + wait_timeout: '{{ _openflake_wait_timeout }}' + release_state: present + # Only when a password was pinned via extra_vars: it rides inside + # release_values, and helm task args would otherwise echo it. Normal + # chart-generated runs keep their output for debugging. + no_log: '{{ _openflake_admin_password | length > 0 }}' + +# When no hostname was supplied, OpenShift picked one. The backend was +# installed pointing BASE_URL/CORS_ORIGINS at the in-cluster Service, so read +# the real hostname back and run a second pass. Helm is idempotent, so later +# runs converge to a no-op rather than churning the deployment. +# Retried: the Route object can exist for a moment before the router has +# assigned it a hostname. +- name: Look up the Route created for this release + kubernetes.core.k8s_info: + api_version: route.openshift.io/v1 + kind: Route + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/part-of=openflake' + register: _openflake_route_info + retries: '{{ _openflake_verify_retries }}' + delay: '{{ _openflake_verify_delay }}' + until: >- + (_openflake_route_info.resources | default([]) | length) > 0 + and ((_openflake_route_info.resources | first).spec.host | default('')) | length > 0 + when: + - _openflake_route_enabled | bool + - not _openflake_route_host + +- name: Record the hostname OpenShift generated + ansible.builtin.set_fact: + _openflake_generated_host: >- + {{ (_openflake_route_info.resources | default([]) | first | default({})).spec.host | default('') }} + when: + - _openflake_route_enabled | bool + - not _openflake_route_host + +# Without this the reconcile below is skipped silently: BASE_URL and +# CORS_ORIGINS stay pointed at the in-cluster Service, openflake_public_url +# renders as a bare scheme, and the job still reports success. +- name: Fail when the Route never produced a hostname + ansible.builtin.assert: + that: + - _openflake_generated_host | default('') | length > 0 + fail_msg: >- + The Route for release '{{ _openflake_release_name }}' in namespace + '{{ _openflake_namespace }}' never reported spec.host, so BASE_URL and + CORS_ORIGINS cannot be reconciled with the public hostname. Check the + Route and the cluster's ingress, or set the Route hostname survey + answer explicitly. + quiet: true + when: + - _openflake_route_enabled | bool + - not _openflake_route_host + +- name: Reconcile BASE_URL and CORS_ORIGINS with the generated hostname + kubernetes.core.helm: + release_name: '{{ _openflake_release_name }}' + release_namespace: '{{ _openflake_namespace }}' + chart_ref: '{{ _openflake_chart_path }}' + release_values: >- + {{ _openflake_release_values + | combine({'route': {'host': _openflake_generated_host}}, recursive=True) }} + binary_path: '{{ _openflake_helm_binary | default(omit, true) }}' + host: '{{ _openflake_api_url }}' + api_key: '{{ _openflake_api_key }}' + validate_certs: '{{ _openflake_validate_certs | bool }}' + ca_cert: '{{ _openflake_ca_cert | default(omit, true) }}' + wait: '{{ _openflake_wait | bool }}' + wait_timeout: '{{ _openflake_wait_timeout }}' + release_state: present + # Only when a password was pinned via extra_vars: it rides inside + # release_values, and helm task args would otherwise echo it. Normal + # chart-generated runs keep their output for debugging. + no_log: '{{ _openflake_admin_password | length > 0 }}' + when: _openflake_generated_host | default('') | length > 0 + +- name: Record the public URL + ansible.builtin.set_fact: + openflake_public_url: >- + {{ (_openflake_route_tls_enabled | bool) | ternary('https://', 'http://') + ~ (_openflake_route_host or _openflake_generated_host | default('')) }} + when: _openflake_route_enabled | bool + +- name: Verify the deployment + ansible.builtin.include_tasks: verify.yml + when: _openflake_verify | bool + +# The chart owns the admin password unless one was supplied, so the only +# authoritative copy lives in the Secret it rendered. +# +# The login is printed below so demo users can copy it straight out of the +# job output. That is a deliberate trade for a demo workload on an ephemeral +# cluster -- AAP retains job output and shows it to anyone with read access +# on the job, so do not reuse this playbook for anything long-lived without +# revisiting it. The fetch stays no_log so only the admin password is +# exposed: the same Secret also carries SECRET_KEY and POSTGRESQL_PASSWORD, +# which nobody needs to read off the screen. +- name: Read the credentials back out of the chart-managed Secret + kubernetes.core.k8s_info: + kind: Secret + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/part-of=openflake' + register: _openflake_secret_info + no_log: true + +- name: Decode the admin password + ansible.builtin.set_fact: + _openflake_resolved_admin_password: >- + {{ ((_openflake_secret_info.resources | default([]) | first | default({})).data | default({})).ADMIN_PASSWORD + | default('') | b64decode }} + no_log: true + +- name: Report how to reach OpenFlake + ansible.builtin.debug: + msg: + # default(..., true) so an empty string falls through to the hint too, + # not just an undefined variable. + - 'OpenFlake URL: {{ openflake_public_url | default("no Route - use the in-cluster Service", true) }}' + - 'OpenFlake username: {{ _openflake_admin_username }}' + - 'OpenFlake password: {{ _openflake_resolved_admin_password | default("not found - read it from the Secret in the namespace", true) }}' + - 'OpenFlake namespace: {{ _openflake_namespace }}' diff --git a/infrastructure/openflake/tasks/preflight.yml b/infrastructure/openflake/tasks/preflight.yml new file mode 100644 index 000000000..65c21f1ad --- /dev/null +++ b/infrastructure/openflake/tasks/preflight.yml @@ -0,0 +1,120 @@ +--- +# default(..., true) treats an empty string as unset, so an unset +# openflake_helm_binary falls back to a PATH lookup. +- name: Resolve the helm binary + ansible.builtin.set_fact: + _openflake_helm_bin: '{{ _openflake_helm_binary | default("helm", true) }}' + +- name: Check for the helm binary + ansible.builtin.command: + cmd: '{{ _openflake_helm_bin }} version --short' + register: _openflake_helm_check + changed_when: false + failed_when: false + +# command only returns rc when it actually execs. A missing binary fails +# before that and returns a dict with no rc at all, so this defaults to 1 +# rather than reading an attribute that may not exist. +- name: Normalise the result of the helm check + ansible.builtin.set_fact: + _openflake_helm_rc: '{{ _openflake_helm_check.rc | default(1) | int }}' + +# kubernetes.core.helm shells out to the helm CLI. Product Demos EE bakes it +# into /usr/local/bin (see execution_environments/apd-ee-27.yml), so this only +# trips when the job runs on some other EE. +- name: Fail when helm is unavailable + ansible.builtin.fail: + msg: | + Could not run '{{ _openflake_helm_bin }} version --short' + (rc={{ _openflake_helm_rc }}). + + kubernetes.core.helm shells out to the helm CLI. Product Demos EE + installs it into /usr/local/bin, so either: + - run this job template on Product Demos EE (the organization + default, which is what it uses when no EE is set); or + - set openflake_helm_binary to an absolute path to helm on the EE + you are using. + + Error: {{ _openflake_helm_check.stderr | default('', true) + or _openflake_helm_check.msg | default('no error reported') }} + when: _openflake_helm_rc | int != 0 + +- name: Report the helm version in use + ansible.builtin.debug: + msg: >- + Using helm {{ _openflake_helm_check.stdout | default('') | trim }} + at '{{ _openflake_helm_bin }}' + +- name: Confirm the chart directory exists + ansible.builtin.stat: + path: '{{ _openflake_chart_path }}/Chart.yaml' + register: _openflake_chart_stat + +- name: Fail when the chart is missing + ansible.builtin.fail: + msg: >- + No chart found at '{{ _openflake_chart_path }}' + (expected Chart.yaml there). + when: not _openflake_chart_stat.stat.exists + +# The k8s modules read K8S_AUTH_SSL_CA_CERT themselves, but helm does not -- +# and it needs a path on disk, so an inline PEM has to be spilled to a file. +- name: Resolve the cluster CA for helm + when: _openflake_ca_raw | length > 0 + block: + - name: Create a temp file for an inline CA certificate + ansible.builtin.tempfile: + state: file + suffix: .crt + register: _openflake_ca_tmp + when: _openflake_ca_is_inline | bool + + - name: Write the inline CA certificate + ansible.builtin.copy: + dest: '{{ _openflake_ca_tmp.path }}' + mode: '0600' + content: '{{ _openflake_ca_raw }}' + when: _openflake_ca_is_inline | bool + + - name: Record the CA path helm should use + ansible.builtin.set_fact: + _openflake_ca_cert: >- + {{ _openflake_ca_tmp.path if (_openflake_ca_is_inline | bool) else _openflake_ca_raw }} + + - name: Confirm the CA file exists + ansible.builtin.stat: + path: '{{ _openflake_ca_cert }}' + register: _openflake_ca_stat + + - name: Fail when a CA was supplied but is not readable + ansible.builtin.assert: + that: + - _openflake_ca_stat.stat.exists + fail_msg: >- + K8S_AUTH_SSL_CA_CERT resolved to '{{ _openflake_ca_cert }}' + but no such file exists. + quiet: true + +# Doubles as an authentication check: fails fast with a clear error if the +# credentials are missing or expired, rather than letting helm fail later +# with a less obvious message. +- name: Query the cluster + kubernetes.core.k8s_cluster_info: + register: _openflake_cluster_info + +- name: Report the connected cluster + ansible.builtin.debug: + msg: >- + Connected to Kubernetes + {{ _openflake_cluster_info.version.server.kubernetes.gitVersion + | default('unknown') }} + +- name: Fail when the cluster has no Route API but a Route was requested + ansible.builtin.fail: + msg: >- + openflake_route_enabled is true but the cluster does not serve + route.openshift.io/v1, so this is not an OpenShift cluster. + when: + - _openflake_route_enabled | bool + - (_openflake_cluster_info.apis | default({}) | length) > 0 + - "'route.openshift.io/v1' not in _openflake_cluster_info.apis" diff --git a/infrastructure/openflake/tasks/uninstall.yml b/infrastructure/openflake/tasks/uninstall.yml new file mode 100644 index 000000000..cedd08589 --- /dev/null +++ b/infrastructure/openflake/tasks/uninstall.yml @@ -0,0 +1,110 @@ +--- +# The namespace comes from a free-text survey field and this play deletes it +# outright, so prove the release is actually in there before touching +# anything. A typo'd namespace should fail here, not take an unrelated +# project with it. Checked up front because the helm uninstall below removes +# the very labels this looks for. +- name: Look for resources belonging to this release + kubernetes.core.k8s_info: + kind: '{{ item }}' + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/part-of=openflake' + register: _openflake_ownership_probe + # Workloads only. The chart's Secret carries the same labels, but k8s_info + # would pull its .data along with it for no benefit here. + loop: + - Deployment + - StatefulSet + +- name: Refuse to continue when the namespace holds no OpenFlake release + ansible.builtin.assert: + that: + - (_openflake_ownership_probe.results | map(attribute='resources') | map('length') | sum) > 0 + fail_msg: >- + No resources labelled app.kubernetes.io/instance={{ _openflake_release_name }}, + app.kubernetes.io/part-of=openflake were found in namespace + '{{ _openflake_namespace }}'. Refusing to uninstall: either the release + is already gone, or the namespace is wrong and removing it would destroy + something else. Check the OpenFlake namespace survey answer. + quiet: true + +- name: Uninstall the OpenFlake release + kubernetes.core.helm: + release_name: '{{ _openflake_release_name }}' + release_namespace: '{{ _openflake_namespace }}' + binary_path: '{{ _openflake_helm_binary | default(omit, true) }}' + host: '{{ _openflake_api_url }}' + api_key: '{{ _openflake_api_key }}' + validate_certs: '{{ _openflake_validate_certs | bool }}' + ca_cert: '{{ _openflake_ca_cert | default(omit, true) }}' + wait: '{{ _openflake_wait | bool }}' + wait_timeout: '{{ _openflake_wait_timeout }}' + release_state: absent + +# `helm uninstall --wait` returns once the API objects are deleted, but pods +# can linger through their termination grace period. Confirm they are gone +# before touching the namespace, so a delete does not race the teardown. +- name: Wait for the release's workloads to disappear + kubernetes.core.k8s_info: + kind: '{{ item }}' + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/part-of=openflake' + register: _openflake_leftovers + retries: '{{ _openflake_verify_retries }}' + delay: '{{ _openflake_verify_delay }}' + until: (_openflake_leftovers.resources | default([]) | length) == 0 + loop: + - Deployment + - StatefulSet + - Pod + +# `helm uninstall` leaves both PVCs behind: the attachments claim carries +# helm.sh/resource-policy=keep, and the Postgres claim belongs to the +# StatefulSet's volumeClaimTemplate. +- name: Delete the persistent volume claims + when: + - _openflake_remove_pvcs | bool + # Skipped when the namespace is going away anyway: deleting the claims and + # then the namespace means waiting out the same teardown twice. + - not (_openflake_remove_namespace | bool) + block: + - name: Find the claims belonging to this release + kubernetes.core.k8s_info: + kind: PersistentVolumeClaim + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/part-of=openflake' + register: _openflake_pvcs + + - name: Delete each claim + kubernetes.core.k8s: + state: absent + api_version: v1 + kind: PersistentVolumeClaim + namespace: '{{ _openflake_namespace }}' + name: '{{ item.metadata.name }}' + wait: true + loop: '{{ _openflake_pvcs.resources | default([]) }}' + loop_control: + label: '{{ item.metadata.name }}' + +- name: Remove the namespace + kubernetes.core.k8s: + state: absent + api_version: v1 + kind: Namespace + name: '{{ _openflake_namespace }}' + wait: true + wait_timeout: '{{ _openflake_namespace_delete_timeout | int }}' + when: _openflake_remove_namespace | bool + +- name: Report the teardown + ansible.builtin.debug: + msg: >- + OpenFlake release '{{ _openflake_release_name }}' removed from + namespace '{{ _openflake_namespace }}'. diff --git a/infrastructure/openflake/tasks/verify.yml b/infrastructure/openflake/tasks/verify.yml new file mode 100644 index 000000000..bcd145fe6 --- /dev/null +++ b/infrastructure/openflake/tasks/verify.yml @@ -0,0 +1,31 @@ +--- +- name: Wait for PostgreSQL to report a ready replica + kubernetes.core.k8s_info: + kind: StatefulSet + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/component=postgresql' + register: _openflake_pg_status + retries: '{{ _openflake_verify_retries }}' + delay: '{{ _openflake_verify_delay }}' + until: >- + (_openflake_pg_status.resources | default([]) | length) > 0 + and ((_openflake_pg_status.resources[0].status.readyReplicas | default(0)) | int) >= 1 + +- name: Wait for the backend and frontend to report available replicas + kubernetes.core.k8s_info: + kind: Deployment + namespace: '{{ _openflake_namespace }}' + label_selectors: + - 'app.kubernetes.io/instance={{ _openflake_release_name }}' + - 'app.kubernetes.io/component={{ item }}' + register: _openflake_deploy_status + retries: '{{ _openflake_verify_retries }}' + delay: '{{ _openflake_verify_delay }}' + until: >- + (_openflake_deploy_status.resources | default([]) | length) > 0 + and ((_openflake_deploy_status.resources[0].status.availableReplicas | default(0)) | int) >= 1 + loop: + - backend + - frontend diff --git a/infrastructure/setup.yml b/infrastructure/setup.yml index 27a269149..1083afd39 100644 --- a/infrastructure/setup.yml +++ b/infrastructure/setup.yml @@ -965,6 +965,63 @@ controller_templates: required: true default: aap + - name: "Infrastructure | OpenFlake" + description: >- + Deploys OpenFlake -- a lightweight ITSM platform with a + ServiceNow-compatible REST API -- on OpenShift via its Helm chart. + The chart generates the admin password on first install and keeps it + across upgrades; the job output reports the URL and credentials. + Set Operation to uninstall to remove the release and its namespace. + # Labels must already exist in controller_labels (common/setup.yml); + # the job template module does not create them. + labels: + - infrastructure + - openshift + job_type: run + organization: Ansible Product Demos (APD) + inventory: Ansible Product Demos Inventory + credentials: + - OpenShift Credential + project: Ansible Product Demos + playbook: infrastructure/openflake/provision.yml + notification_templates_started: Telemetry + notification_templates_success: Telemetry + notification_templates_error: Telemetry + survey_enabled: true + survey: + name: '' + description: '' + spec: + - question_name: Operation + type: multiplechoice + variable: openflake_operation + required: true + default: install + choices: + - install + - uninstall + - question_name: OpenFlake namespace + question_description: >- + OpenShift project/namespace for the OpenFlake deployment. + Created if it does not exist. + type: text + variable: openflake_namespace + required: true + default: openflake + - question_name: Route hostname + question_description: >- + Leave blank to let OpenShift generate one from the cluster's + wildcard apps domain. + type: text + variable: openflake_route_host + required: false + default: '' + - question_name: OpenFlake image tag + type: text + variable: openflake_image_tag + required: true + default: stable + controller_workflows: - name: Infrastructure | ROSA - Lifecycle (Create) description: >-