Zum Inhalt springen
Trainingslager IT-Trainingslager

Anhang A: Spickzettel

Stand des Buchs: Backstage 1.55.0 (@backstage/[email protected], neues Frontend- und Backend-System) unter Node 24 LTS (24.21.0) mit Yarn 4 über Corepack, Forgejo 16.0.6 (rootless) in Docker, PostgreSQL 16.4. Namen entsprechen dem Lab: Org kranich, App ~/backstage-lab/portal. Alle Passwörter und Tokens sind Lab-Werte.

Lab-Umgebung

source ~/backstage-lab/setup/env.sh       # LAB, PORTAL, PATH, FORGEJO, Tokens, bs()
~/backstage-lab/setup/check.sh            # Gelände prüfen, Exit-Code = Anzahl ✘
~/backstage-lab/setup/up.sh               # Forgejo starten, Admin, Bot, Bot-Token
~/backstage-lab/setup/seed.sh             # Org kranich + sendungs-api, tracking-web
~/backstage-lab/setup/seed.sh --reset     # beide Repos auf Stand Tag 0
~/backstage-lab/setup/mkrepo.sh kranich/org ~/backstage-lab/tag04/org
~/backstage-lab/setup/portal.sh start     # yarn start im Hintergrund, wartet
~/backstage-lab/setup/portal.sh restart   # nach yarn add / app-config*.yaml
~/backstage-lab/setup/portal.sh stop|status
~/backstage-lab/setup/portal.sh logs 300  # letzte 300 Zeilen von portal.log
docker start bs-postgres                  # ab Tag 13 vor jedem Start

env.sh definiert bs – ein curl gegen die Backstage-API mit dem Lab-Token:

bs() { local p="$1"; shift; curl -sf -H "Authorization: Bearer $BACKSTAGE_TOKEN" \
  "$@" "$BACKSTAGE/api/$p"; }
bs catalog/entities?limit=1                       # GET
bs catalog/refresh -X POST -H 'Content-Type: application/json' -d '{…}'
  • bs nutzt curl -f und verschluckt Fehlertexte. Für die Fehlermeldung direkt curl -s -H "Authorization: Bearer $BACKSTAGE_TOKEN" … und jq .error.message.
  • env.sh wächst: ab Tag 7 export PATH="$LAB/venv/bin:$PATH", ab Tag 12 lädt es setup/oidc-client, ab Tag 13 tag13/pg.env.
  • portal.sh start überschreibt portal.log. Farbcodes entfernen: sed 's/\x1b\[[0-9;]*m//g'. Wer yarn start von Hand startet, muss vorher env.sh laden (sonst leere ${LAB}, ${FORGEJO_TOKEN}, kein mkdocs).
  • Alle sed -i '' im Buch sind macOS-Schreibweise, unter Linux sed -i.

Ports, URLs und Lab-Werte

Was Wert im Lab
Frontend (Dev) / Backend http://localhost:3000 / http://localhost:7007
Produktionsbetrieb (Tag 13) alles auf http://localhost:7007
Forgejo Web / API http://127.0.0.1:3300 / …/api/v1
Forgejo-Container, Volumes bs-forgejo, bs-forgejo-data, bs-forgejo-conf
Forgejo-Admin lab-admin / lab-admin-pw-123, in env.sh als $ADMIN
Bot backstage-bot, Token in ~/backstage-lab/setup/forgejo-token
Forgejo-User (Tag 12) anna.berger, thomas.zachmann / lab-user-pw-123
Lab-Token (Service) lab-cli-token-0123456789abcdef, Subjekt lab-cli
Lese-Token (Tag 12) lab-ro-token-0123456789abcdef, Subjekt lab-readonly
PostgreSQL (Tag 13) bs-postgres, 127.0.0.1:5432, backstage / lab-pg-pw-123
kind (Tag 10) Cluster backstage-lab, ~/backstage-lab/tag10/kubeconfig
SQLite (bis Tag 12) ~/backstage-lab/data/<plugin>.sqlite
Gast-Identität user:development/guest; Tag 4–11 user:default/thomas.zachmann
Seite Pfad
Katalog / bis Tag 8, /catalog ab Tag 9 (dann / = Startseite)
Entity-Seite /catalog/<namespace>/<kind>/<name>
Katalog gefiltert /?filters[kind]=template (ab Tag 9 /catalog?…)
Templates, Wizard, Task /create, /create/templates/default/<name>, /create/tasks/<id>
APIs, Graph, Docs /api-docs, /catalog-graph, /docs
TechDocs einer Entity /docs/default/component/<name>
Registrieren, Suche /catalog-import, /search?query=…
Visualizer /visualizer (ab Tag 9 heißt der Eintrag App-Struktur)

Forgejo-Datei-URL für den Katalog: http://127.0.0.1:3300/kranich/<repo>/src/branch/main/catalog-info.yaml (GitHub …/blob/main/…, GitLab …/-/blob/main/…). OIDC-Callback: http://localhost:7007/api/auth/oidc/handler/frame.

Repos in kranich: sendungs-api, tracking-web (Tag 0), zustell-worker (Tag 1), sendungsverfolgung (Tag 2), katalog, zustell-app (Tag 3), org (Tag 4), templates, lager-api, lager-worker, tour-api (Tag 5), lager-scanner, lager-etiketten, paket-api (Tag 6).

Forgejo-Einzeiler

GIT=http://lab-admin:[email protected]:3300            # Lab-Wert!
git clone -q $GIT/kranich/sendungs-api.git
git -c user.name="Lab Admin" -c [email protected] commit -qam "…"
R=$FORGEJO/api/v1/repos/kranich/lager-api
curl -sf -u "$ADMIN" "$R" | jq '{full_name, default_branch, private}'
curl -sf -u "$ADMIN" "$R/contents" | jq -r '.[].path'
curl -sf -u "$ADMIN" "$R/raw/catalog-info.yaml"
curl -s -H "Authorization: token $FORGEJO_TOKEN" "$FORGEJO/api/v1/user" | jq .login
docker exec "$FORGEJO_NAME" forgejo admin user create --username anna.berger \
  --password lab-user-pw-123 --email [email protected] \
  --must-change-password=false
curl -s "$FORGEJO/.well-known/openid-configuration" | jq .issuer

Entity-Kinds

Jede Entity hat apiVersion, kind, metadata, spec; mehrere Entities pro Datei mit --- trennen. uid, etag und relations setzt der Katalog (Tag 2).

Kind apiVersion spec im Buch Tag
Component backstage.io/v1alpha1 type, lifecycle, owner (Pflicht), system 1, 2
API backstage.io/v1alpha1 type, lifecycle, owner, system, definition 1, 8
System backstage.io/v1alpha1 owner, domain 2
Domain backstage.io/v1alpha1 owner 2
Resource backstage.io/v1alpha1 type, owner, system 2, 3
Group backstage.io/v1alpha1 type, parent, profile, children (Pflicht) 4
User backstage.io/v1alpha1 profile (displayName, email), memberOf 4
Location backstage.io/v1alpha1 targets (relativ zur Datei) 3, 5
Template scaffolder.backstage.io/v1beta3 owner, type, parameters, steps, output 5
  • metadata.name: Folgen aus [a-zA-Z0-9], getrennt durch -_., höchstens 63 Zeichen; Großbuchstaben erlaubt, Leerzeichen nicht (Tag 2).
  • spec.type ist frei (service, website, database, external-service, organization, department, team); API-Typen mit eigener Ansicht: openapi, asyncapi, graphql, grpc, trpc – alles andere als Text (Tag 8).
  • definition inline als |-Block (Tag 2) oder definition: { $text: ./openapi.yaml } relativ zur catalog-info.yaml (Tag 1, 8).
  • Group: nur parent pflegen, children: [] lassen; Mitglieder per User-memberOf oder Group-members (Tag 4).
Metadaten-Feld Wirkung (Tag 2)
metadata.title Anzeigename statt name
metadata.description Beschreibung in About-Karte und Suche
metadata.tags Chips und Filter Tags; nur a-z0-9+#, mit - verbunden
metadata.labels Karte Labels, eigene mit Firmen-Präfix (kranich.de/…)
metadata.links Karte Links: url, title, icon (dashboard, docs, …)
metadata.annotations Schnittstelle zu Plugins
metadata.namespace Standard default

Annotations

Annotation Bedeutung Tag
backstage.io/techdocs-ref: dir:. mkdocs.yml liegt neben catalog-info.yaml 7
backstage.io/kubernetes-id: <id> Tab Kubernetes, Label-Selector im Cluster 2, 10
backstage.io/kubernetes-label-selector Alternative bei Namenskollisionen 10
backstage.io/managed-by-location Location, aus der die Entity stammt (Katalog) 2, 3
backstage.io/managed-by-origin-location ursprünglich registrierte Location 3
backstage.io/source-location Quelle für View Source (Katalog) 2
backstage.io/edit-url, …/view-url Stift und View Source (Katalog) 2
backstage.io/orphan: "true" Entity ohne Quelle (Katalog) 3

Relationen

Feld in spec Relation Gegenrichtung
owner ownedBy ownerOf
system, domain partOf hasPart
dependsOn dependsOn dependencyOf
providesApis providesApi apiProvidedBy
consumesApis consumesApi apiConsumedBy
parent (Group) childOf parentOf
memberOf (User), members (Group) memberOf hasMember

Abfragen und Oberfläche arbeiten mit Relationen, nicht mit spec (Tag 4). Catalog Graph: Start mit MAX DEPTH 1; Simplified aus zeigt beide Richtungen (Tag 2). Include indirect ownership folgt parentOf nach unten (Tag 4).

Entity-Referenzen

Form Beispiel Wo
kind:namespace/name group:default/team-sendung Relationen, Filter, Tokens
kind:name resource:sendungs-db dependsOn (Kind nötig)
name team-sendung owner (→ group), system, domain
kind/namespace/name component/default/sendungs-api API-Pfad by-name/…
  • Der Katalog ergänzt Namespace default und den Standard-Kind des Felds (Tag 2).
  • In API-Filtern nur die volle Form: relations.dependsOn=resource:default/sendungs-db findet etwas, resource:sendungs-db nicht (Tag 2).
  • OwnerPicker und EntityPicker liefern volle Referenzen, im erzeugten Repo steht dann owner: group:default/team-sendung (Tag 5, 6).

Katalog-API

bs catalog/entities | jq -r '.[] | "\(.kind)\t\(.metadata.name)"'
bs 'catalog/entities?filter=kind=component'
bs 'catalog/entities?filter=kind=component,spec.lifecycle=production'   # UND
bs 'catalog/entities?filter=kind=api&filter=spec.type=website'          # ODER
bs 'catalog/entities?filter=kind=group,kind=user&fields=kind,metadata.name'
bs 'catalog/entities?filter=spec.system=sendungsverfolgung'
bs 'catalog/entities?filter=relations.ownedBy=group:default/team-web'
bs 'catalog/entities?filter=relations.dependsOn=resource:default/sendungs-db'
bs 'catalog/entities?filter=metadata.annotations.backstage.io/orphan=true'
bs 'catalog/entities?fields=kind,metadata.name,status' \
  | jq '.[] | select(.status.items)'                       # Processing-Fehler
bs catalog/entities/by-name/component/default/sendungs-api
bs catalog/entities/by-name/component/default/tracking-web/ancestry
bs catalog/entities/by-uid/$uid -X DELETE -w '%{http_code}\n'           # 204
bs catalog/entities/by-refs -X POST -H 'Content-Type: application/json' \
  -d '{"entityRefs":["group:default/it"],"fields":["kind"]}'      # fehlt: null
bs 'catalog/entity-facets?facet=kind'          # auch spec.owner, metadata.tags,
bs 'catalog/entity-facets?facet=relations.ownedBy'                # relations.…
bs catalog/refresh -X POST -H 'Content-Type: application/json' \
  -d '{"entityRef":"component:default/tracking-web"}'
bs catalog/locations | jq -r '.[].data | "\(.id) \(.type) \(.target)"'
bs catalog/locations -X POST -H 'Content-Type: application/json' \
  -d "{\"type\":\"url\",\"target\":\"$URL\"}"          # entities: [] = asynchron
curl -s -H "Authorization: Bearer $BACKSTAGE_TOKEN" \
  -H 'Content-Type: application/json' -X POST \
  "$BACKSTAGE/api/catalog/locations?dryRun=true" \
  -d "{\"type\":\"url\",\"target\":\"$URL\"}" | jq -r '.error.message // "ok"'
bs catalog/locations/$id -X DELETE -w '%{http_code}\n'                  # 204
  • catalog/locations listet nur per API/GUI registrierte Locations, nicht die aus der Konfiguration oder vom Provider (Tag 3).
  • Delete einer Entity hilft nur kurz: Die Location liefert sie mit neuer uid zurück. Dauerhaft weg erst mit der Location (Unregister Location) (Tag 3).
  • Fehler einer Entity: .status.items[] | .error.cause.message (Tag 2).

Weitere API-Endpunkte

bs scaffolder/v2/actions | jq -r '.[].id'
bs scaffolder/v2/templating-extensions | jq -r '.filters | keys[]'
bs 'scaffolder/v2/tasks?limit=1'                     # .tasks[0].status, .createdBy
bs 'scaffolder/v2/tasks?createdBy=user:default/thomas.zachmann'
bs 'scaffolder/v2/tasks?limit=3&order=desc:created_at'
bs scaffolder/v2/tasks -X POST -H 'Content-Type: application/json' -d @auftrag.json
bs scaffolder/v2/tasks/$ID                           # status, spec.parameters
bs scaffolder/v2/tasks/$ID/events | jq -r '.[].body.message'
bs scaffolder/v2/tasks/$ID/cancel -X POST            # {"status":"cancelled"}
bs scaffolder/v2/dry-run -X POST -H 'Content-Type: application/json' -d @-
bs techdocs/sync/default/component/sendungs-api -N   # Build-Log als SSE
bs techdocs/metadata/techdocs/default/component/sendungs-api | jq .etag
bs techdocs/static/docs/default/component/sendungs-api/index.html
bs 'search/query?term=sendung&types%5B0%5D=software-catalog&filters%5Bkind%5D=API'
bs kubernetes/clusters | jq -c '.items[]'
bs kubernetes/services/sendungs-api -X POST -H 'Content-Type: application/json' \
  -d '{"entity":{"kind":"Component","metadata":{"name":"sendungs-api"}}}'
bs proxy/forgejo/orgs/kranich/repos | jq -r '.[].full_name'
bs 'bereitschaft/heute?team=team-sendung'            # eigenes Plugin (Tag 11)
curl -s -H 'X-Requested-With: XMLHttpRequest' "$BACKSTAGE/api/auth/guest/refresh" \
  | jq .backstageIdentity.identity                   # .token = Gast-Token
curl -s "$BACKSTAGE/.backstage/health/v1/readiness"  # ohne Login
bs catalog/entities/unprocessed/pending | jq '.entities | length'    # Tag 14
bs catalog/entities/unprocessed/failed  | jq '.entities | length'
bs devtools/info | jq -r .backstageVersion
bs devtools/config | jq .config.integrations         # Secrets als <secret>
Endpunkt Body bzw. Hinweis Tag
POST scaffolder/v2/tasks templateRef, values, optional secrets 6
POST scaffolder/v2/dry-run template (JSON), values, directoryContents (base64) 6
POST permission/authorize {"items":[{"id","permission":{"type":"basic","name"}}]} 12
GET auth/oidc/start?env=development 302 zu Forgejo /login/oauth/authorize 12

Ohne Token antwortet jedes Plugin mit 401 Missing credentials, mit falschem Token Illegal token (Tag 0, 11). Tasks über den Lab-Token haben createdBy: null, im GUI Owner Unknown (Tag 6).

app-config: Dateien und Zusammenführen

Regel Tag
app-config.yaml (eingecheckt) < app-config.local.yaml (per .gitignore lokal) 0
Objekte werden Schlüssel für Schlüssel gemischt, Listen komplett ersetzt 3, 9
Keine doppelten Top-Level-Keys: neue Blöcke anhängen, sonst yq -i 4, 7
${VAR} aus der Umgebung; fehlt sie, verschwindet der Schlüssel still 0, 13
${VAR:-default} Ersatzwert, $$ echtes Dollarzeichen 13
--config a.yaml --config b.yaml: später gewinnt 13
APP_CONFIG_<pfad> mit _ als Trenner, Wert als JSON oder Text; gewinnt immer 13
app.extensions nur in app-config.yaml, nie in der local-Datei 9
Reihenfolge: ändern → config:check → portal.sh restart 14
config:print maskiert visibility: secret als <secret>; --with-secrets zeigt Klartext 14
cd ~/backstage-lab/portal
yarn backstage-cli config:print --lax | grep -A5 '^techdocs:'     # zusammengeführt
yarn backstage-cli config:print --frontend --format json 2>/dev/null \
  | jq -r '.app.extensions[] | keys[0]'                       # was der Browser sieht
yarn backstage-cli config:print --config app-config.yaml \
  --config app-config.local.yaml --config app-config.production.yaml \
  2>/dev/null | yq '.backend.database'                        # Secrets: <secret>
yarn backstage-cli config:check                               # Schema, YAML
yarn backstage-cli config:check --strict --config app-config.yaml \
  --config k.yaml                    # auch unbekannte Schlüssel (Fehlalarme möglich)
yarn backstage-cli config:schema --merge --format json > schema.json  # in Datei!
grep -c '^auth:' app-config.local.yaml                        # 1 = kein Duplikat
yq -i 'del(.auth)' app-config.local.yaml

app-config: Katalog

catalog:
  processingInterval: { seconds: 20 }     # Standard zufällig 100–150 s (Tag 3)
  # orphanStrategy: keep                  # Standard delete; Aufräumjob alle 30 s
  rules:
    - allow: [Component, System, API, Resource, Location, Domain]
    - allow: [Template]                   # global, aber nur aus diesem Repo (Tag 5)
      locations:
        - type: url
          pattern: http://127.0.0.1:3300/kranich/templates/**
  locations:                              # ersetzt die Liste aus app-config.yaml!
    - type: file                          # relativ zu packages/backend
      target: ../../examples/entities.yaml
    - type: url
      target: http://127.0.0.1:3300/kranich/katalog/src/branch/main/locations.yaml
    - type: url
      target: http://127.0.0.1:3300/kranich/org/src/branch/main/org.yaml
      rules:                              # gilt nur für genau diese Datei
        - allow: [User, Group]
    - type: url
      target: http://127.0.0.1:3300/kranich/templates/src/branch/main/templates.yaml
  providers:
    gitea:
      kranich:                            # Task gitea-provider:kranich:refresh
        host: 127.0.0.1:3300              # muss zu integrations.gitea passen
        organization: kranich
        branch: main                      # Standard main
        catalogPath: catalog-info.yaml    # Standard catalog-info.yaml
        schedule:                         # Pflicht
          frequency: { minutes: 1 }
          timeout: { minutes: 1 }
  • create-app erlaubt nur Component, System, API, Resource, Location; rules an einer Location gelten nicht für ihre targets – deshalb pattern (Tag 2, 5).
  • type: file liest vom Dateisystem des Backends, ${LAB} geht (Tag 3).
  • Sammel-Repos (katalog, templates) nutzen bewusst nicht catalog-info.yaml, damit der Provider sie nicht mit den globalen Regeln einliest (Tag 3, 5).
  • Provider entfernen löscht seine Entities (orphanProviderStrategy, Standard delete) (Tag 3).

app-config: Integration, Backend, Auth

integrations:
  gitea:
    - host: 127.0.0.1:3300
      baseUrl: http://127.0.0.1:3300
      username: backstage-bot
      password: ${FORGEJO_TOKEN}
backend:
  auth:
    externalAccess:
      - type: static
        options:
          token: ${BACKSTAGE_TOKEN}
          subject: lab-cli                # Service-Principal: umgeht die Policy
      - type: static
        options:
          token: lab-ro-token-0123456789abcdef
          subject: lab-readonly
        accessRestrictions:               # plugin, permission, permissionAttribute
          - plugin: catalog
            permissionAttribute: { action: read }
  cors:
    origin: http://localhost:3000         # aus app-config.yaml; passt zu app.baseUrl
  logger:                                 # Tag 14, ohne Neustart wirksam
    overrides:
      - matchers: { plugin: catalog }     # Wert oder Regex in /…/
        level: debug
  database:                               # bis Tag 12: SQLite, eine Datei je Plugin
    client: better-sqlite3
    connection:
      directory: ${LAB}/data
auth:
  environment: development
  session:
    secret: ${AUTH_SESSION_SECRET}        # Pflicht für OIDC (Tag 12)
  providers:
    guest: {}                             # Tag 4: userEntityRef: user:default/…
    oidc:
      development:                        # Name aus auth.environment
        metadataUrl: http://127.0.0.1:3300/.well-known/openid-configuration
        clientId: ${OIDC_CLIENT_ID}
        clientSecret: ${OIDC_CLIENT_SECRET}
        signIn:
          resolvers:                      # der Reihe nach probiert
            - resolver: emailMatchingUserEntityProfileEmail
            - resolver: emailLocalPartMatchingUserEntityName

Ab Tag 13 in der local-Datei und in app-config.production.yaml:

backend:
  database:
    client: pg                            # pluginDivisionMode: database (Standard)
    connection:
      host: ${POSTGRES_HOST}
      port: ${POSTGRES_PORT}
      user: ${POSTGRES_USER}
      password: ${POSTGRES_PASSWORD}

Guest-Provider-Schlüssel: userEntityRef (Standard user:development/guest), ownershipEntityRefs, dangerouslyAllowOutsideDevelopment (Tag 4, 13). OIDC-Modul: metadataUrl, clientId, clientSecret, optional prompt, additionalScopes (Tag 12).

app-config: TechDocs, Suche, Kubernetes, Proxy, Permission

techdocs:                                 # Vorlage: runIn: 'docker'
  builder: local                          # CI-Setup: external
  generator:
    runIn: local                          # mkdocs aus dem PATH (venv)
  publisher:
    type: local                           # Objektspeicher: awsS3, googleGcs
search:
  collators:                              # Standard PT10M
    catalog:
      schedule:
        frequency: { minutes: 1 }
        timeout: { minutes: 5 }
    techdocs:
      schedule:
        frequency: { minutes: 1 }
        timeout: { minutes: 5 }
kubernetes:
  serviceLocatorMethod:
    type: multiTenant
  clusterLocatorMethods:
    - type: config
      clusters:
        - name: backstage-lab
          url: $K8S_URL                   # beim Anhängen von der Shell eingesetzt
          authProvider: serviceAccount
          serviceAccountToken: $K8S_TOKEN
          caData: $K8S_CA                 # Lab-Alternative: skipTLSVerify: true
          skipMetricsLookup: true         # kind hat keinen metrics-server
proxy:
  endpoints:
    /forgejo:                             # → /api/proxy/forgejo/…
      target: http://127.0.0.1:3300/api/v1
      headers:
        Authorization: token ${FORGEJO_TOKEN}
      allowedMethods: [GET]               # credentials: require ist Standard
permission:
  enabled: true                           # steht schon in app-config.yaml
devTools:                                 # Tag 14
  scheduledTasks:
    plugins: [catalog, search]
bereitschaft:                             # eigenes Plugin (Tag 11)
  teams:
    team-sendung: [anna.berger, ben.kraus]

Software Templates

apiVersion: scaffolder.backstage.io/v1beta3
kind: Template
metadata:
  name: node-service
  title: Node.js-Service
spec:
  owner: plattform
  type: service
  parameters:                             # je Listeneintrag ein Wizard-Schritt
    - title: Service
      required: [name, description, owner]
      properties:
        name:
          type: string
          pattern: '^[a-z][a-z0-9-]{2,30}$'
          ui:autofocus: true
        description:
          type: string
        owner:
          type: string
          ui:field: OwnerPicker
          ui:options:
            catalogFilter: { kind: Group, spec.type: team }
    - title: Repository
      required: [repoUrl]
      properties:
        repoUrl:
          type: string
          ui:field: RepoUrlPicker         # → 127.0.0.1:3300?owner=kranich&repo=x
          ui:options:
            allowedHosts: ['127.0.0.1:3300']
            allowedOwners: [kranich]
  steps:
    - id: fetch
      action: fetch:template
      input:
        url: ./skeleton
        values:
          name: ${{ parameters.name }}
          description: ${{ parameters.description }}
          owner: ${{ parameters.owner }}
    - id: publish
      action: publish:gitea
      input:
        repoUrl: ${{ parameters.repoUrl }}
        description: ${{ parameters.description }}
        defaultBranch: main
    - id: register
      action: catalog:register
      input:
        repoContentsUrl: ${{ steps.publish.output.repoContentsUrl }}
        catalogInfoPath: catalog-info.yaml   # ohne führenden /
  output:
    links:
      - title: Repository in Forgejo
        url: ${{ steps.publish.output.repoContentsUrl }}
      - title: Im Katalog öffnen
        icon: catalog
        entityRef: ${{ steps.register.output.entityRef }}
    text:
      - title: Nächste Schritte
        content: "**${{ parameters.name }}** ist angelegt."
Action Eingaben im Buch Ausgaben / Hinweis Tag
fetch:template url, values, optional targetPath rendert Nunjucks 5
fetch:template:file url, targetPath (Pflicht), values eine Datei 6
fetch:plain url, targetPath kopiert ohne Rendern 6
debug:log message, listWorkspace Log-Zeile 6
publish:gitea repoUrl, description (Pflicht), defaultBranch, repoVisibility, gitCommitMessage, gitAuthorName, gitAuthorEmail remoteUrl, repoContentsUrl, commitHash 5
catalog:register repoContentsUrl, catalogInfoPath entityRef 5
kranich:ticket:create title, team, token, delaySeconds ticketId (eigene Action) 6
Feld bzw. Schlüssel Wirkung Tag
OwnerPicker + catalogFilter Gruppen aus dem Katalog, liefert group:default/… 5
EntityPicker catalogFilter, defaultKind, allowArbitraryValues: false 6
EntityNamePicker prüft nur das Format, nicht ob der Name frei ist 6
RepoUrlPicker allowedHosts, allowedOwners; Typ aus integrations 5
ui:field: Secret Wert in ${{ secrets.<name> }}, im Log *** 6
ui:widget: checkboxes type: array, items.enum, uniqueItems 6
each: ${{ parameters.liste }} Step je Eintrag, Wert in ${{ each.value }} 6
if: ${{ parameters.ci }} sonst „Skipping step … if condition was false” 6

Nunjucks: ${{ values.name }}, ${{ values.description | dump }} (JSON-String, sicher für YAML/JSON), {% if … %}…{% endif %}, {%- if %} (entfernt den Umbruch davor), ${{ 'a' if x else 'b' }}. Filter im Buch: parseRepoUrl, parseEntityRef, pick('name'), projectSlug, dump, join(', ') (Tag 5, 6). Templates neu einlesen: bs catalog/refresh … template:default/<name> oder location:default/kranich-templates (Tag 5, 6).

GUI unter Create: Tabs Tasks, Actions, Templating Extensions, Template Editor (Karten Load Template Directory – nur Chrome/Edge –, Template Form Playground, Custom Field Explorer); Task-Seite: Cancel, START OVER, HIDE LOGS (Tag 5, 6).

TechDocs

# mkdocs.yml neben catalog-info.yaml
site_name: Sendungs-API
nav:
  - Überblick: index.md
  - Betrieb: betrieb.md
plugins:
  - techdocs-core
python3 -m venv ~/backstage-lab/venv
~/backstage-lab/venv/bin/pip install -q mkdocs-techdocs-core     # 1.7.1 (Tag 7)
mkdocs build -q -d "$(mktemp -d)"                               # lokal prüfen
npx -y @techdocs/[email protected] generate --no-docker                # → ./site
npx @techdocs/[email protected] publish --publisher-type awsS3 \
  --storage-name kranich-techdocs --entity default/component/sendungs-api \
  --directory ./site                                    # CI, nicht live getestet
  • Ablauf: prepare (Git-Stand) → generate (mkdocs build) → publish; der lokale Publisher schreibt nach node_modules/@backstage/plugin-techdocs-backend/static/docs/.
  • Gebaut wird beim Lesen: Der Tab fragt techdocs/sync, gebaut wird nur bei neuem Commit (etag), pro Entity höchstens einmal pro Minute geprüft (Tag 7).
  • Admonitions !!! note, !!! warning, !!! tip gehen, Mermaid nicht (Tag 7).
  • Der Such-Kollator liest search/search_index.json gebauter Docs (Tag 8).

Suche

Thema Fakt Tag
Engine mit SQLite Lunr im RAM; Log Postgres search engine is not supported 8
Engine mit Postgres search-backend-module-pg, Tabelle documents 13
Kollatoren search_index_software_catalog, search_index_techdocs 8
Lunr nach Neustart ca. 30 s HTTP 500 MissingIndexError 8
Lunr-Eigenheiten Filter macht Suchbegriff optional; bis 2 Tippfehler 8
Treffer-Felder type, document (title, text, kind, location …), rank 8

Das Suchmodal öffnet nur per Klick auf Search in der Sidebar, kein Tastenkürzel (Tag 8).

Frontend-System

app.packages: all bindet jedes Frontend-Plugin aus packages/app/package.json automatisch ein (role: frontend-plugin mit Feature-Export); include:/exclude: schränken das ein (Tag 10, 11). Extension-IDs: <art>:<plugin>/<name>, sichtbar im Visualizer (Tree, Detailed, Text, Show Disabled) (Tag 9).

app:
  extensions:                             # nur in app-config.yaml pflegen
    - page:home:
        config:
          path: /
          defaultConfig:                  # gilt bis zum ersten EDIT des Users
            - component: GettingStarted
              column: 0
              row: 2
              width: 6
              height: 5
    - home-page-widget:home/random-joke: false      # abschalten
    - page:app-visualizer:
        config:
          title: App-Struktur                       # Seitentitel und Sidebar
    - entity-card:catalog/about: true               # Reihenfolge der Liste
    - entity-card:catalog-graph/relations:
        config:
          type: info                                # rechte Spalte
          title: Beziehungen
          height: 280
    - entity-card:org/ownership:
        config:
          initialRelationAggregation: aggregated
    - api:home/visits: true                         # ab Werk aus
    - app-root-element:home/visit-listener: true
Extension-ID Rolle Tag
page:catalog, page:catalog/entity Katalog, Entity-Seite 0, 9
page:home Startseite (/home, ab Tag 9 /) 9
page:catalog-import, page:scaffolder, page:techdocs Seiten der Sidebar 9
page:search, page:notifications, page:user-settings Seiten 9
page:app-visualizer Visualizer / App-Struktur 9
home-page-widget:home/toolkit config.tools[]: url, label, icon 9
home-page-widget:home/world-clock config.clockConfigs[]: label, timeZone 9
home-page-widget:home/random-joke externe API, im Buch aus 9
entity-content:catalog/overview Tab Overview, Eingang cards 9, 11
entity-content:kubernetes/kubernetes Tab Kubernetes 10
entity-card:catalog/about, …catalog-graph/relations Karten 9
entity-card:org/ownership Karte Ownership 4, 9
entity-card:bereitschaft/heute eigene Karte, config.type: info 11
theme:app/light, theme:app/dark, theme:app/kranich Themes 9
sign-in-page:app Sign-in-Seite (Standard nur guest) 12
api:home/visits, app-root-element:home/visit-listener Besuchsverlauf 9

Home-Layout-Komponenten: HomePageSearchBar, HomePageToolkit, HomePageWorldClock, HomePageStarredEntities, HomePageRecentlyVisited, HomePageMostVisited und eigene über HomePageWidgetBlueprint (params.name) (Tag 9).

Baustein Paket Tag
createFrontendModule, createFrontendPlugin, ApiBlueprint @backstage/frontend-plugin-api 9, 11, 12
HomePageWidgetBlueprint @backstage/plugin-home-react/alpha 9
ThemeBlueprint, SignInPageBlueprint @backstage/plugin-app-react 9, 12
EntityCardBlueprint (filter, loader) @backstage/plugin-catalog-react/alpha 11
createUnifiedTheme, genPageTheme, palettes @backstage/theme 9
OAuth2.create @backstage/core-app-api 12
  • Module stehen in packages/app/src/App.tsx unter createApp({ features: […] }). Ein Modul überschreibt nur Extensions seines Plugins (pluginId: 'app' für Theme und Sign-in) (Tag 9, 12).
  • Sidebar-Reihenfolge in modules/nav/Sidebar.tsx: nav.take('page:…'), Rest mit nav.rest({ sortBy: 'title' }); Logo in LogoFull.tsx/LogoIcon.tsx (Tag 9).
  • Frontend-Code lädt yarn start beim Speichern neu; Fehler in Extension-IDs nur in der Browser-Konsole (Tag 9).

Plugins und eigener Code

cd ~/backstage-lab/portal
yarn --cwd packages/backend add @backstage/plugin-catalog-backend-module-gitea
yarn --cwd packages/backend add @backstage/plugin-scaffolder-backend-module-gitea
yarn --cwd packages/backend add @backstage/plugin-auth-backend-module-oidc-provider \
  @backstage/backend-plugin-api
yarn --cwd packages/app add @backstage/theme@^0.7.3
yarn --cwd packages/app add @backstage/core-app-api
yarn new                                                     # interaktives Menü
yarn new --select backend-plugin --option pluginId=bereitschaft
yarn new --select scaffolder-backend-module --option moduleId=kranich
grep -n 'backend.add' packages/backend/src/index.ts
Muster Ergebnis Tag
backend.add(import('<paket>')); Backend-Plugin oder -Modul aktiv 3, 5
backend.add(import('./modules/forgejoAuth')); eigenes Modul aus src/modules 12
yarn new backend-plugin plugins/<id>-backend, Eintrag in index.ts, API /api/<id> 11
yarn new frontend-plugin plugins/<id>, nur Abhängigkeit von packages/app 11
Paketname @internal/backstage-plugin-<id>[-backend], workspace:^ 11
Backend-Baustein Paket Tag
createBackendPlugin, createBackendModule, coreServices @backstage/backend-plugin-api 6, 11, 12
createTemplateAction, scaffolderActionsExtensionPoint @backstage/plugin-scaffolder-node 6
authProvidersExtensionPoint, createOAuthProviderFactory @backstage/plugin-auth-node 12
PermissionPolicy, policyExtensionPoint (/alpha) @backstage/plugin-permission-node 12
catalogConditions, createCatalogConditionalDecision @backstage/plugin-catalog-backend/alpha 12
InputError (400), NotFoundError (404) @backstage/errors 11
startTestBackend, mockServices, mockCredentials @backstage/backend-test-utils 11
  • Module im Buch: pluginId/moduleId = scaffolder/kranich, auth/forgejo-oidc, permission/kranich-policy (Tag 6, 12).
  • coreServices.rootConfig, .logger, .httpRouter (hängt unter /api/<pluginId> ein), .userInfo (ownershipEntityRefs) (Tag 11, 12).
  • Routen öffnen nur bewusst: httpRouter.addAuthPolicy({ path: '/health', allow: 'unauthenticated' }) (Tag 11).
  • Im Frontend fetchApi mit plugin://<pluginId>/… – Token des Users hängt dran; Config ist dort nur mit @visibility frontend lesbar (Tag 11).
CI=true yarn test plugins/bereitschaft          # ohne Watch-Modus, beide Pakete
yarn tsc                                        # Typen, ohne Fehler keine Ausgabe
yarn --cwd packages/app lint                    # no-undeclared-imports
yarn lint:all                                   # yarn lint prüft nur Diff zu origin
yarn backstage-cli versions:bump                # Upgrade (Tag 14)

Login und Berechtigungen

Permission (Name) Wirkung im Buch Tag
catalog.entity.read Gast: ALLOW 12
catalog.entity.delete nur group:default/plattform 12
catalog.location.delete nur Plattform (Unregister löscht die Location) 12
scaffolder.task.create nur Plattform, sonst kein Choose 12
catalog.entity.refresh Challenge: nur Owner (isEntityOwner) 12
catalog.location.create Registrieren im GUI 1
  • Allow-all-Policy aus create-app: @backstage/plugin-permission-backend-module-allow-all-policy – ersetzen durch backend.add(import('./modules/permissionPolicy')) (Tag 12).
  • Service-Principals (lab-cli) fragt die Policy nie: einschränken nur über accessRestrictions; permission/authorize lehnt service-Credentials ab (Tag 12).
  • Das Frontend fragt vorab POST /api/permission/authorize und blendet aus oder sperrt (aria-disabled); die echte Sperre ist das Backend (403) (Tag 12).
  • Forgejo meldet email_verified nur im ID-Token – eigenes Auth-Modul mit profileTransform statt Standard-OIDC-Modul (nicht beide mit providerId: 'oidc') (Tag 12).
  • Sign Out beendet nur die Backstage-Sitzung; zum User-Wechsel privates Fenster (Tag 12).

Betrieb

source ~/backstage-lab/tag13/pg.env                 # POSTGRES_HOST/PORT/USER/PASSWORD
docker run -d --name bs-postgres -p "127.0.0.1:$POSTGRES_PORT:5432" \
  -v bs-postgres-data:/var/lib/postgresql/data \
  -e POSTGRES_USER -e POSTGRES_PASSWORD postgres:16.4-alpine
docker exec bs-postgres pg_isready -h 127.0.0.1 -U backstage
docker exec bs-postgres psql -U backstage -lqt | cut -d'|' -f1 | grep backstage
sql() { docker exec bs-postgres psql -U backstage -d "$1" -Atc "$2"; }
sql backstage_plugin_catalog 'select count(*) from final_entities'
sql backstage_plugin_search 'select type, count(*) from documents group by 1'
docker exec bs-postgres pg_dump -U backstage -Fc backstage_plugin_catalog \
  > catalog.dump                                    # Portal vorher stoppen
docker exec -i bs-postgres pg_restore -U backstage -d backstage_plugin_catalog \
  < catalog.dump
yarn tsc && yarn build:backend         # → packages/backend/dist/bundle.tar.gz
cd ~/backstage-lab/release && tar xzf ../portal/packages/backend/dist/bundle.tar.gz
cp -c -R ../portal/node_modules .                   # APFS-Klon statt Installation
nohup node packages/backend --config app-config.yaml \
  --config app-config.local.yaml --config app-config.production.yaml \
  > ~/backstage-lab/prod.log 2>&1 & echo $! > ~/backstage-lab/prod.pid
APP_CONFIG_app_title='Kranich Portal (Prod)' node packages/backend …   # Override
NODE_ENV=production node packages/backend …         # Logs als JSON
kill $(cat ~/backstage-lab/prod.pid)
yarn build-image                                    # nur beschrieben (Tag 13)
Thema Fakt Tag
Datenbanken je Plugin backstage_plugin_<id>, DB-User braucht CREATEDB 13
ohne CREATEDB backend.database.pluginDivisionMode: schema 13
Katalog-Tabellen final_entities, refresh_state, relations, locations, search 13
Verlust beim DB-Wechsel Sterne, Benachrichtigungen, alte Tasks 13
Produktion app.baseUrl = backend.baseUrl = http://localhost:7007 13
file-Locations relativ zum Arbeitsverzeichnis: Dev packages/backend, Prod Wurzel 13
Image node:24-trixie-slim, .dockerignore schließt *.local.yaml aus 13
Endpunkt Bedeutung Tag
/.backstage/health/v1/liveness Prozess lebt 13
/.backstage/health/v1/readiness gestartet (sonst 503), prüft die DB nicht 0, 13

Fehlersuche und Upgrade

~/backstage-lab/setup/portal.sh logs 2000 | sed 's/\x1b\[[0-9;]*m//g' \
  | awk '$3=="warn" || $3=="error" {print $2, $3}' | sort | uniq -c   # Plugin, Level
LOG_LEVEL=debug ~/backstage-lab/setup/portal.sh restart     # error|warn|info|debug
yarn backstage-cli info                                     # Versionen für Tickets
curl -s -D - -o /dev/null -H "Origin: $APP" "$BACKSTAGE/api/catalog/entities" \
  | grep -i '^access-control-allow-origin'                  # CORS prüfen
lsof -nP -iTCP:7007 -sTCP:LISTEN                            # wer belegt den Port?
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: token $FORGEJO_TOKEN" \
  $FORGEJO/api/v1/user                                      # Bot-Token gültig?
Symptom Ebene Werkzeug (Tag 14)
Seite leer, Login scheitert Frontend↔︎Backend Browser-Konsole (F12), curl -H Origin
Portal startet nicht Konfiguration config:check, portal.sh logs
Entity alt, rote Karte Katalog status.items, Inspect entity, Log
Entity fehlt ganz Katalog Unprocessed Entities, Log
401/403/„not allowed” Integration Dry-Run, Token gegen Forgejo
Task rot Scaffolder Task-Log, tasks/<id>/events – erster Fehler zählt
  • Grundrauschen im Lab: Event subscribe request failed with status 404, does not contain a catalog-info.yaml (katalog, org, templates), Postgres search engine is not supported, Index for techdocs was not created (Tag 14).
  • DevTools (@backstage/plugin-devtools, …-devtools-backend) und Unprocessed Entities (@backstage/plugin-catalog-unprocessed-entities, …-catalog-backend-module-unprocessed): Reiter Info, Config, Scheduled Tasks (Trigger), Unprocessed Entities mit Pending (nie angekommen) und Failed (letzter Lauf ohne Ergebnis). Permissions devtools.*, catalog.entities.unprocessed.read (Tag 14).
  • Scheduled Task Idle heißt nicht fehlerfrei: Der Gitea-Provider fängt Fehler selbst ab (Tag 14).
cd ~/backstage-lab/portal
git add -A && git commit -qm "Stand vor Upgrade"
cat backstage.json                                      # aktuelles Release
curl -s https://versions.backstage.io/v1/tags/main/manifest.json | jq -r .releaseVersion
yarn backstage-cli versions:bump --release 1.55.3 --skip-install
git diff --stat
yarn install && yarn tsc && yarn --cwd packages/app lint && CI=true yarn test
yarn backstage-cli config:check && ~/backstage-lab/setup/portal.sh restart

Was sich ändert: Upgrade Helper (https://backstage.github.io/upgrade-helper/?from=1.55.0&to=1.55.3) für die Vorlage, node_modules/@backstage/<paket>/CHANGELOG.md je Paket, bei Minor-Releases die Release Notes unter https://backstage.io/docs/releases/v1.56.0/. Ein Commit pro Upgrade, Rückweg per git revert (Tag 14).

Fehlerbilder

Symptom Ursache Abhilfe Tag
yarn install: got@patch:got@npm%3A11.8.2 … ENOENT kaputtes @yarnpkg/[email protected] resolutions auf 4.9.1 0
401 Missing credentials / Illegal token kein bzw. falscher Token bs oder env.sh laden 0, 11
/catalog 404 Katalog liegt bis Tag 8 auf / Pfad / nehmen 1
/ 404 nach app.extensions in local Liste ersetzt die aus app-config.yaml Eintrag dort pflegen 9
gelbe Warnung „relations … can’t be found” Owner-Gruppe fehlt im Katalog Gruppe anlegen (kranich/org) 1, 4
is not of an allowed kind for that location catalog.rules Kind erlauben, Regel an Location 2, 3, 4
"metadata.name" is not valid Leerzeichen o. Ä. im Namen Namensregel einhalten 2
/spec must have required property 'owner' owner fehlt ergänzen 2
rote Fehlerkarte, alter Stand bleibt Processing-Fehler status.items, Log, Revert 2, 3
PlaceholderProcessor threw an error $text zeigt ins Leere Pfad korrigieren 3
detected conflicting entityRef location:… Provider und Hand-Registrierung Location unregistern 3, 5
Detected conflicting entityRef group:… Entity in zwei Dateien eine Quelle löschen 4
Owned zeigt 0 Gast ist user:development/guest userEntityRef bzw. Login 4
nur publish:github Gitea-Modul fehlt im Scaffolder scaffolder-backend-module-gitea 5
…/src/branch/catalog-info.yaml, 400 catalogInfoPath mit / ohne führenden / 5
409 Conflict beim Publish Repo existiert schon anderer Name, START OVER 5
does not support dry-run Action ohne supportsDryRun erwartet 6
Umlaute als für im Template Editor btoa-Übertragung in 1.55 echter Lauf ist korrekt 6
Docker.ping() failed im TechDocs-Tab runIn: docker ohne Socket runIn: local + venv 7
spawn mkdocs ENOENT Portal ohne env.sh gestartet portal.sh restart 7
{"updated":false} direkt nach Push Prüfung max. 1×/min je Entity später erneut öffnen 7
Such-API 500 MissingIndexError Lunr nach Neustart leer ca. 30 s warten 8
neue Entity nicht in der Suche Kollator-Zeitplan (PT10M) search.collators.*.schedule 8
INVALID_EXTENSION_CONFIG_KEY (Konsole) Tippfehler in Extension-ID ID im Visualizer prüfen 9
Lint: must be declared in dependencies Import ohne Eintrag yarn --cwd packages/app add … 9
Kubernetes-Tab „Backend (HTTP 404)” kein Block kubernetes: Cluster konfigurieren 10
Kubernetes 403 /api/v1/pods ServiceAccount ohne Rechte ClusterRole + Binding 10
Test: No path for routeRef…catalog:entity EntityRefLink ohne Route mountedRoutes im Test 11
oidc/start 500, requires session support auth.session.secret fehlt Secret setzen 12
user profile does not contain an email email_verified nicht im Userinfo eigenes Auth-Modul 12
Login scheitert trotz Forgejo-Konto keine passende User-Entity User in org.yaml 12
does not allow 'service' credentials Lab-Token an permission/authorize User-Token nehmen 12
access is restricted to plugin(s) accessRestrictions erwartet 12
kein Choose, Unregister gesperrt Policy: DENY Gruppe plattform 12
port is already allocated anderes Postgres auf 5432 Port in pg.env ändern 13
guest provider cannot be used outside… NODE_ENV ≠ development dangerouslyAllowOutsideDevelopment (Lab) 13
APIs 500, readiness 200 Postgres weg DB starten, erholt sich selbst 13
backend.baseUrl is set to a localhost URL Produktion mit localhost echte baseUrl 13
Warnungen Postgres search engine…, kubernetes…, Event subscribe…404 SQLite, kein Cluster im Lab erwartet 0
YAMLParseError: All mapping items must start at the same column verrutschte Einrückung config:check, Einrückung 14
portal.sh wartet bis Timeout yarn start an Config-Fehler beendet Strg+C, portal.sh logs 30 14
password fehlt in config:print Env-Variable leer oder vertippt Variable prüfen 14
Schlüssel wirkungslos ({ second: 20 }) Tippfehler im Namen config:check --strict 14
401 Unauthorized an Locations, gitea-provider … refresh failed Bot-Token abgelaufen/falsch Token erneuern 14
Unable to read url … configure an integration Host passt nicht (localhost ≠ 127.0.0.1) URL bzw. integrations.*.host 14
No matching integration configuration for host repoUrl mit fremdem Host (API) Host aus integrations 14
Credentials for the gitea ${host} required. Integration ohne password Token setzen 14
Entity fehlt, kein status.items nie gültig verarbeitet Unprocessed Pending 14
irreführende Login-Meldung, Konsole: CORS backend.cors.origin falsch Override löschen 14
portal.sh ✔, aber Backend tot, EADDRINUSE Port 7007 belegt lsof, Prozess beenden 14
--strict: additionalProperty=providers Gitea-Provider ohne Schema Fehlalarm 14