iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎪

Centralizing CI/CD Information in the Backstage Developer Portal

に公開

Overview

Backstage is an OSS framework for building developer portals. It has ~27K GitHub stars and is a CNCF incubating project.

https://backstage.io/docs/overview/what-is-backstage/

To advance cloud-native application development more efficiently, as discussed in the OSS-based home cloud configuration, it is necessary to master various products for CI/CD tools and code management. This increases the effort required to navigate between multiple documents and web UIs. By using Backstage, information essential for development—such as Git repository code, CI/CD infrastructure, and documentation—can be aggregated into the Backstage portal, allowing for a comprehensive view of the entire project.

Since there are already many articles on how to set up Backstage and its basic usage, this article will focus on the aforementioned goal and verify whether CI/CD-related information can be aggregated.

Setting up Backstage

Backstage consists of a frontend and a backend, but there are two types: the new system and the one used previously (the older one is referred to as the "old system" or "legacy system" in the documentation).

For more details, refer to the following article.

https://techblog.ap-com.co.jp/entry/2023/12/23/012101

Since the new system is easier for introducing plugins, it is generally recommended. However, since some of the plugins used this time do not seem to support the new system yet, we will use the old frontend and backend for this verification.

Backstage setup proceeds according to https://backstage.io/docs/getting-started/. After installing the set of tools listed in Prerequisites, we use a slightly older version, create-app:0.5.1, to install the package containing Backstage in order to use the old frontend and backend. (The latest version at the time of writing was 0.5.17.)

$ npx @backstage/create-app@0.5.10

? Enter a name for the app [required] backstage

Creating the app...

 Checking if the directory is available:
  checking      backstage ✔

 Creating a temporary app directory:

 Preparing files:
  copying       .dockerignore ✔
  templating    .eslintrc.js.hbs ✔
  ...

Once the setup is complete, the backstage directory will contain the necessary packages and configuration files for operating Backstage. Hereafter, this backstage directory will be referred to as the project root directory.

The configuration of Backstage is described in app-config.yaml, which is created after setup. In this article, to allow access to the Backstage server using the domain name backstage.ops.com, we will rewrite the parts that are set to localhost in app-config.yaml.

app-config.yaml
app:
  baseUrl: http://backstage.ops.com:3000
backend:
  baseUrl: http://backstage.ops.com:7007
  cors:
    origin: http://backstage.ops.com:3000

Introducing plugins

Without a concrete application, it's difficult to visualize what information should be aggregated. Here, we will use the application from a previous article, Building and Testing a Simple CI/CD Environment in a Local Environment (Tekton Edition), as an example. In that article, the following tools were used to develop applications running on a K8s cluster via CI/CD:

  • Application code is managed in GitLab.
  • Tekton is used to build container images from the code.
  • Built images are managed in Harbor.
  • ArgoCD is used to deploy to the target cluster.

In this flow, the tools related to application development are GitLab, Tekton, Harbor, ArgoCD, and the K8s cluster. If these can be aggregated on the Backstage portal, it becomes convenient to manage the entire project comprehensively. Fortunately, plugins already exist to integrate each tool with Backstage, so we will look at what information can be retrieved by introducing these.

Kubernetes plugin

Kubernetes integration is one of Backstage's core features, allowing you to view K8s resources based on labels from the Backstage portal by communicating with a specific K8s cluster. While plugin activation and configuration are fundamentally described in the documentation, the following site also provides a well-organized summary of the items to be configured, so we will proceed by referring to both.

https://roadie.io/backstage/plugins/kubernetes/

From here on, plugin installations will be performed using yarn and executed from the project root directory.
First, install the K8s frontend plugin.

yarn --cwd packages/app add @backstage/plugin-kubernetes

Add the following code to packages/app/src/components/catalog/EntityPage.tsx.

packages/app/src/components/catalog/EntityPage.tsx
import { EntityKubernetesContent } from '@backstage/plugin-kubernetes';

// You can add the tab to any number of pages, the service page is shown as an
// example here
const serviceEntityPage = (
  <EntityLayout>
    {/* other tabs... */}
    <EntityLayout.Route path="/kubernetes" title="Kubernetes">
      <EntityKubernetesContent refreshIntervalMs={30000} />
    </EntityLayout.Route>
  </EntityLayout>
);

Next, install the backend plugin.

yarn --cwd packages/backend add @backstage/plugin-kubernetes-backend

Create a new file packages/backend/src/plugins/kubernetes.ts.

packages/backend/src/plugins/kubernetes.ts
import { KubernetesBuilder } from '@backstage/plugin-kubernetes-backend';
import { Router } from 'express';
import { PluginEnvironment } from '../types';
import { CatalogClient } from '@backstage/catalog-client';

export default async function createPlugin(
  env: PluginEnvironment,
): Promise<Router> {
  const catalogApi = new CatalogClient({ discoveryApi: env.discovery });
  const { router } = await KubernetesBuilder.createBuilder({
    logger: env.logger,
    config: env.config,
    catalogApi,
    discovery: env.discovery,
    permissions: env.permissions,
  }).build();
  return router;
}

Add to packages/backend/src/index.ts.

packages/backend/src/index.ts
// ..
import kubernetes from './plugins/kubernetes';

async function main() {
  // ...
  const kubernetesEnv = useHotMemoize(module, () => createEnv('kubernetes'));
  // ...
  apiRouter.use('/kubernetes', await kubernetes(kubernetesEnv));

Now that the plugin installation is complete, next we proceed with the configuration on the K8s cluster side. Prepare a K8s cluster separate from the server running Backstage, and create the ServiceAccount, Role, and RoleBinding used for the connection between Backstage and the K8s cluster.

serviceaccount.yml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: backstage-sa
  namespace: backstage-sample

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: backstage-sample-clusterrole
rules:
- apiGroups: [""]
  resources: ["pods", "services"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: backstage-sample-clusterrolebinding
subjects:
- kind: ServiceAccount
  name: backstage-sa
  namespace: backstage-sample
roleRef:
  kind: ClusterRole
  name: backstage-sample-clusterrole
  apiGroup: rbac.authorization.k8s.io

Set a token for this ServiceAccount.

apiVersion: v1
kind: Secret
metadata:
  name: sa-secret
  namespace: backstage-sample
  annotations:
    kubernetes.io/service-account.name: backstage-sa
type: kubernetes.io/service-account-token

You can retrieve the token from the created secret with the following command, so make a note of it.

kubectl -n backstage-sample get secrets sa-secret -o yaml | yq -r ".data.token" | base64 -d

Next, add kubernetes to Backstage's app-config.yaml and describe the connection settings for the cluster.

  • url: Specify the connection URL for the K8s control plane. This can be confirmed by running kubectl cluster-info on the K8s cluster's control plane. It usually matches the K8s API server endpoint.
  • serviceAccountToken: Specify the SA token confirmed above. You can write the value directly, or load it from an environment variable as shown below.

For other items, refer to the configuration.

app-config.yaml
kubernetes:
  serviceLocatorMethod:
    type: 'multiTenant'
  clusterLocatorMethods:
    - type: 'config'
      clusters:
        - url: https://192.168.3.131:6443
          name: k8s
          authProvider: 'serviceAccount'
          skipTLSVerify: true
          skipMetricsLookup: true
          serviceAccountToken: ${k8S_TOKEN}

Now that the preparations are complete, let's try creating some appropriate resources and see if they can be confirmed from Backstage.

There are several ways to associate a Backstage entity with K8s resources, but here we will use the method of specifying a label selector in annotations. We will create a Component entity, which is a Backstage-side resource, and set backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example' in its annotations.

examples/k8s.yml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: k8s-example
  annotations:
    backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example'
spec:
  type: service
  lifecycle: experimental
  owner: guests
  system: examples

Add the following to the catalog in app-config.yaml to load the above.

app-config.yaml
catalog:
  locations:
    - type: file
      target: ../../examples/k8s.yml

In this case, K8s-side resources configured with the backstage-project: k8s-example label will be associated with the above entity. To confirm operation, create appropriate deployments and a service (svc).

nginx.yml
kind: Deployment
metadata:
  name: nginx
  namespace: backstage-sample
  labels:
    app: nginx
    backstage-project: k8s-example
spec:
  selector:
    matchLabels:
      app: nginx
      backstage-project: k8s-example
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
        backstage-project: k8s-example
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
  namespace: backstage-sample
  labels:
    app: nginx
    backstage-project: k8s-example
spec:
  selector:
    app: nginx
    backstage-project: backstage-example
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

Run yarn dev in the project root directory to start the Backstage frontend and backend. Access backstage.ops.com:3000 from your browser and check the created Component entity k8s-example. You should see that a kubernetes tab has been added, and you can confirm the pods and services deployed to the cluster.

An error message regarding resources that cannot be retrieved due to insufficient permissions will be displayed at the top of the page. This is not an issue since we won't be using them this time, but if you want to retrieve these resources as well, you will need to add permissions to the Role on the K8s side.

There was a problem retrieving some Kubernetes resources for the entity: k8s-example. This could mean that the Error Reporting card is not completely accurate.

Errors:
Cluster: k8s

Error fetching Kubernetes resource: '/api/v1/configmaps', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/api/v1/limitranges', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/api/v1/resourcequotas', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/autoscaling/v2/horizontalpodautoscalers', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/batch/v1/jobs', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/batch/v1/cronjobs', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/networking.k8s.io/v1/ingresses', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/apps/v1/statefulsets', error: UNKNOWN_ERROR, status code: 403
Error fetching Kubernetes resource: '/apis/apps/v1/daemonsets', error: UNKNOWN_ERROR, status code: 403

Since you can associate a Backstage entity with specific deployments or services, you can, for example, check whether pods are running normally when a frontend application is operating on K8s. This offers the benefit of saving the effort of searching for pods related to a project, especially in cases where many pods exist within the same cluster.

Argocd plugin

https://roadie.io/backstage/plugins/argo-cd/?utm_source=backstage.io&utm_medium=marketplace&utm_campaign=argo-cd

The above plugin can be used for integration with ArgoCD. With this plugin, you can retrieve the status of a specified application from the integrated ArgoCD and check its health, sync status, update history, and more directly from the Backstage portal.

Install the frontend plugin:

yarn --cwd packages/app add @roadiehq/backstage-plugin-argo-cd

Add the following to packages/app/src/components/catalog/EntityPage.tsx.

packages/app/src/components/catalog/EntityPage.tsx
import {
  EntityArgoCDOverviewCard,
  isArgocdAvailable
} from '@roadiehq/backstage-plugin-argo-cd';

const overviewContent = (
  <Grid container spacing={3} alignItems="stretch">
  ...
    <EntitySwitch>
      <EntitySwitch.Case if={e => Boolean(isArgocdAvailable(e))}>
        <Grid item sm={4}>
          <EntityArgoCDOverviewCard />
        </Grid>
      </EntitySwitch.Case>
    </EntitySwitch>
  ...
  </Grid>
);

Next, install the backend plugin:

yarn --cwd packages/backend add @roadiehq/backstage-plugin-argo-cd-backend

Create packages/backend/src/plugins/argocd.ts.

packages/backend/src/plugins/argocd.ts
import { createRouter } from '@roadiehq/backstage-plugin-argo-cd-backend';
import { PluginEnvironment } from '../types';

export default async function createPlugin({
  logger,
  config,
}: PluginEnvironment) {
  return await createRouter({ logger, config });
}

Update packages/backend/src/index.ts.

packages/backend/src/index.ts
import argocd from './plugins/argocd';
...

const argocdEnv = useHotMemoize(module, () => createEnv('argocd'));
...
apiRouter.use('/argocd', await argocd(argocdEnv));

The connection information for the target ArgoCD is specified in app-config.yaml. Here, we'll assume the target domain is argocd.ops.com.

app-config.yml
proxy:
  endpoints:
    '/argocd/api':
      target: https://argocd.ops.com:32566/api/v1/
      changeOrigin: true
      secure: false
      headers:
        Cookie:
          $env: ARGOCD_TOKEN

argocd:
  username: <username>
  password: <password>
  appLocatorMethods:
    - type: 'config'
      instances:
        - name: argoInstance1
          url: https://argocd.ops.com:32566
          token: ${ARGOCD_TOKEN}

Next, prepare the application and other resources on the ArgoCD side for verification.

application.yml
---
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: backstage-sample-app
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://gitlab.ops.com/kube/backstage-example.git
    targetRevision: HEAD
    path: argocd
  destination:
    server: https://kubernetes.default.svc
    namespace: backstage-sample

Configuration for the backstage user and role used for the connection.

argocd-cm
apiVersion: v1
data:
  accounts.backstage: apiKey,login
  accounts.backstage.enabled: "true"
kind: ConfigMap
metadata:
  labels:
    app.kubernetes.io/name: argocd-cm
    app.kubernetes.io/part-of: argocd
  name: argocd-cm
  namespace: argocd
rbac.yml
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-rbac-cm
  namespace: argocd
  labels:
    app.kubernetes.io/name: argocd-rbac-cm
    app.kubernetes.io/part-of: argocd
data:
  policy.csv: |
    p, role:test-role, applications, create, default/*, allow
    p, role:test-role, applications, get, default/*, allow
    p, role:test-role, applications, update, default/*, allow
    p, role:test-role, applications, delete, default/*, allow
    p, role:test-role, applications, sync, default/*, allow
    p, role:test-role, applications, override, default/*, allow
    g, backstage, role:test-role
  policy.default: role:readonly

Since the deployment manifest will be placed in a self-managed GitLab, we also configure certificates and authentication methods.

repo.yml
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-tls-certs-cm
  namespace: argocd
  labels:
    app.kubernetes.io/name: argocd-cm
    app.kubernetes.io/part-of: argocd
data:
  gitlab.ops.com: |
    -----BEGIN CERTIFICATE-----
    ...
    -----END CERTIFICATE-----

---
apiVersion: v1
kind: Secret
metadata:
  name: gitlab-repo
  namespace: argocd
  labels:
    argocd.argoproj.io/secret-type: repository
stringData:
  type: git
  url: https://gitlab.ops.com/kube/backstage-example.git
  password: <password>
  username: <username>

For verification, place the deployment manifest in the backstage-example.git repository on GitLab.

.
├── argocd
    └── deployment.yml
deployment.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-from-gitlab
  namespace: backstage-sample
  labels:
    app: nginx2
    backstage-project: sample-project
    backstage.io/kubernetes-id: k8s-example
spec:
  selector:
    matchLabels:
      app: nginx2
      backstage-project: sample-project
      backstage.io/kubernetes-id: k8s-example
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx2
        backstage-project: sample-project
        backstage.io/kubernetes-id: k8s-example
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

Once all the above resources are created, set a password for the backstage user on the ArgoCD side and create a token. Also, perform a sync of the application.

argocd login argocd.ops.com:32566 --username admin --password <password> --insecure
argocd account update-password --account backstage --new-password backstage
argocd logout
argocd login argocd.ops.com:32566 --username backstage --password <password> --insecure
argocd account generate-token
argocd app sync backstage-sample-app

Add the following label to the component entity created earlier:

ks8.yml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: k8s-example
  annotations:
    backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example'
+    argocd/app-name: backstage-sample-app
spec:
  type: service
  lifecycle: experimental
  owner: guests
  system: examples

Similar to the K8s plugin, the ArgoCD plugin allows you to specify which ArgoCD resources to associate through several methods. For instance, specifying argocd/app-name as shown above will associate the ArgoCD Application resource corresponding to that name. For other specification methods, refer to https://www.npmjs.com/package/@roadiehq/backstage-plugin-argo-cd.

Finally, since the Backstage-to-ArgoCD connection uses the token of the backstage user created earlier, set it as an environment variable on the Backstage server side with export ARGOCD_TOKEN=....
When you start Backstage with yarn dev and open the entity, information about the specified ArgoCD Application will be displayed on the overview page.

Clicking on it allows you to confirm details such as the repo information set in the application spec.

Clicking the Link will take you to the corresponding Application page in the ArgoCD dashboard.

As with the K8s plugin, details and synchronization status of the ArgoCD application associated with the entity are now visible at a glance. Furthermore, since the actual deployment status and resources can be managed on the ArgoCD side, you can use Backstage for verifying that the deployment is running normally and jump to the ArgoCD project for detailed troubleshooting when anomalies or errors occur.

Tekton plugin

https://janus-idp.io/plugins/tekton/

Several Tekton plugins can be found, but we will use the one mentioned above. This plugin allows you to check the success or failure of Tekton PipelineRun resources on the K8s cluster and view execution logs from Backstage.

Install the frontend plugin:

yarn --cwd packages/app add @janus-idp/backstage-plugin-tekton

Add the following to EntityPage.tsx.

packages/app/src/components/catalog/EntityPage.tsx
import {
  isTektonCIAvailable,
  TektonCI,
} from '@janus-idp/backstage-plugin-tekton';

const cicdContent = (
  0EntitySwitch>
    {/* ... */}
    0EntitySwitch.Case if={isTektonCIAvailable}>
      0TektonCI />
    0/EntitySwitch.Case>
  0/EntitySwitch>
);

Add the following CRs to the kubernetes section in app-config.yml.

app-config.yml
kubernetes:
  customResources:
    - group: 'tekton.dev'
      apiVersion: 'v1'
      plural: 'pipelineruns'
    - group: 'tekton.dev'
      apiVersion: 'v1'
      plural: 'taskruns'

Referencing the documentation, add permissions to the K8s Role to allow access to Tekton resources. Here, we add permissions to the backstage-sample-clusterrole created during the K8s plugin introduction.

serviceaccount.yml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: backstage-sample-clusterrole
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log", "services"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["tekton.dev"]
  resources:
    - pipelineruns
    - taskruns
  verbs:
    - get
    - list

Next, add Pipeline resources on the Tekton side. We will reuse the ones used in Building and Testing a Simple CI/CD Environment in a Local Environment (Tekton Edition). Refer to that article for details.

pipeline.yml
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
  name: backstage-ci-cd
  namespace: backstage-sample
  labels:
    backstage.io/kubernetes-id: k8s-example
spec:
  description: >-
    This pipeline run the sequence of tasks as a pipeline.
    1. Clone the application source from a git repository.
    2. Build an image from Dockerfile and push it to a registry.
    3. Deploy application by argocd sync.
  params:
    - name: repositoryUrl
      type: string
      description: The git repository URL to clone the source.
    - name: branch
      type: string
      description: The branch of the repository.
    - name: context
      description: The path to the build context, used by Kaniko - within the workspace
      default: "./"
    - name: imageName
      description: Image name
    - name: imageTag
      description: Image tag
      default: "latest"
    - name: argocdApplicationName
      description: The name of Argocd application to be synced.
  workspaces:
    - name: shared-data
      description: >-
        This workspace contains the cloned repo files, so they can be read by the
        next task.
    - name: git-credentials
      description: Name of the secret to log in to gitlab.
    - name: harbor-credentials
      description: Name of the secret to log in to harbor.
    - name: argocd-credentials
      description: Name of the secret to log in to argocd.
  tasks:
    - name: git-clone
      taskRef:
        name: git-clone
      workspaces:
        - name: output
          workspace: shared-data
        - name: basic-auth
          workspace: git-credentials
      params:
        - name: url
          value: $(params.repositoryUrl)
        - name: revision
          value: $(params.branch)
        - name: sslVerify
          value: "false"
    - name: build
      taskRef:
        name: kaniko
      runAfter:
        - git-clone
      workspaces:
        - name: source
          workspace: shared-data
        - name: dockerconfig
          workspace: harbor-credentials
      params:
        - name: IMAGE
          value: $(params.imageName):$(params.imageTag)
        - name: CONTEXT
          value: $(params.context)
    - name: deploy
      taskRef:
        name: argocd-sync
      runAfter:
        - git-clone
        - build
      workspaces:
        - name: argocd-basic-auth
          workspace: argocd-credentials
      params:
        - name: applicationName
          value: $(params.argocdApplicationName)

To associate Tekton resources with a Backstage entity, add janus-idp.io/tekton: <BACKSTAGE_ENTITY_NAME> to the entity's annotations.

k8s.yml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: k8s-example
  annotations:
    backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example'
    argocd/app-name: backstage-sample-app
+    janus-idp.io/tekton: k8s-example
spec:
  type: service
  lifecycle: experimental
  owner: guests
  system: examples

On the Tekton side, set backstage.io/kubernetes-id: <BACKSTAGE_ENTITY_NAME> in the labels of the pipeline resource. Note that this is set in labels, not annotations. For other specification methods, refer to https://janus-idp.io/plugins/tekton/#for-administrators.

pipelinerun.yml
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
  name: backstage-ci-cd
  namespace: backstage-sample
  labels:
    backstage.io/kubernetes-id: k8s-example
spec:
  ,,,

Start Backstage and check the CI/CD tab of the entity; you will see that Tekton has been added. Here, you can check the execution results of the Tekton pipeline and each task within it.

Clicking on a stage allows you to check the logs for each task (corresponding to pod logs). The font is a bit small, but you can also download the logs as a text file.

This allows you to check the results of various processes from the Backstage portal, such as linting and testing performed in CI, building container images, uploading to container registries, and triggering ArgoCD.

Harbor plugin

The Harbor plugin allows you to check information about container images stored in Harbor from Backstage. A plugin for Harbor is listed in the Backstage plugin list as one managed by container-registry, but it currently seems to be archived (Reference).

While it's possible to use the archived version, it has some functional issues. Therefore, we will instead use the plugin owned by @digitalist-open-cloud, which was forked from the aforementioned repository.

https://www.npmjs.com/package/@digitalist-open-cloud/backstage-plugin-harbor
https://www.npmjs.com/package/@digitalist-open-cloud/backstage-plugin-harbor-backend

Install the frontend plugin:

yarn --cwd packages/app add @digitalist-open-cloud/backstage-plugin-harbor

Add the following to EntityPage.tsx.

packages/app/src/components/catalog/EntityPage.tsx
import {
  HarborPage,
  HarborWidget,
  isHarborAvailable,
} from '@digitalist-open-cloud/backstage-plugin-harbor'

const serviceEntityPage = (
  <EntityPageLayout>
    // ...
    <EntityLayout.Route path="/harbor" title="Harbor" if={isHarborAvailable}>
      <HarborPage />
    </EntityLayout.Route>
  </EntityPageLayout>
)

The following change adds a widget to the Backstage entity overview. Add this as you like.

packages/app/src/components/catalog/EntityPage.tsx
const overviewContent = (
  <Grid container spacing={6} alignItems="stretch">
    // ...
    <EntitySwitch>
      <EntitySwitch.Case if={isHarborAvailable}>
        <Grid item>
          <HarborWidget />
        </Grid>
      </EntitySwitch.Case>
    </EntitySwitch>
    ...
  </Grid>
)

Install the backend plugin:

yarn --cwd packages/backend add @digitalist-open-cloud/backstage-plugin-harbor-backend

Create a new file packages/backend/src/plugins/harbor.ts.

packages/backend/src/plugins/harbor.ts
import { createRouter } from '@digitalist-open-cloud/backstage-plugin-harbor-backend';
import { Router } from 'express';
import { PluginEnvironment } from '../types';

export default async function createPlugin({
  logger,
  config,
}: PluginEnvironment): Promise<Router> {
  return await createRouter({ logger, config });
}

Update index.ts. Although the site says harborusage, in my testing, harborusage resulted in an error while harbor worked correctly.

packages/backend/src/index.ts
import harbor from './plugins/harbor';
// ...
async function main() {
  // ...
  const harborEnv = useHotMemoize(module, () => createEnv('harbor'));
-  apiRouter.use('/harbor', await harborusage(harborEnv));
+  apiRouter.use('/harbor', await harbor(harborEnv));

Connection information for Harbor is described in app-config.yaml.

app-config.yaml
harbor:
  # This is the traditional way of configuring the Harbor plugin.
  baseUrl: https://harbor.yourdomain.com
  username: ${HARBOR_USERNAME}
  password: ${HARBOR_PASSWORD}

Add goharbor.io/repository-slug to the annotations of the Backstage entity resource, and add the Harbor image you want to associate in the format <project>/<image_name>. Note that the visibility and permissions for the image specified here must be set so that it can be referenced by the Harbor user mentioned above.

k8s.yml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: k8s-example
  annotations:
    backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example'
    argocd/app-name: backstage-sample-app
    janus-idp.io/tekton: k8s-example
+   goharbor.io/repository-slug: k8s/backstage-front
spec:
  type: service
  lifecycle: experimental
  owner: guests
  system: examples

Once you start Backstage with this configuration, a Harbor tab will be added, allowing you to retrieve the tag list, sizes, and vulnerability scan results for the specified image. However, it seems that the number of tags doesn't match exactly with the Harbor side, so there might be constraints such as only a certain number of recent image tags being retrieved.

Clicking Learn more will take you to the corresponding image page in the Harbor web UI.

Similar to ArgoCD, you can use the Backstage portal for a quick check, and jump to the Harbor UI via "Learn more" when you need detailed information.

Reference: Regarding old plugins

I also tested the archived container-registry Harbor plugins (such as @bestsellerit/backstage-plugin-harbor) and confirmed that the tab was added. However, if vulnerability scanning was not enabled on the Harbor side, the following error was displayed in the logs and images could not be retrieved.

[1] 2024-07-28T08:30:30.025Z backstage error Cannot read properties of undefined (reading 'href') type=errorHandler stack=TypeError: Cannot read properties of undefined (reading 'href')
[1]     at <anonymous> (/home/ubuntu/backstage/old/node_modules/@bestsellerit/backstage-plugin-harbor-backend/src/service/artifact.ts:18:73)
[1]     at Array.map (<anonymous>)
[1]     at getArtifacts (/home/ubuntu/backstage/old/node_modules/@bestsellerit/backstage-plugin-harbor-backend/src/service/artifact.ts:16:37)
[1]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[1]     at <anonymous> (/home/ubuntu/backstage/old/node_modules/@bestsellerit/backstage-plugin-harbor-backend/src/service/router.ts:19:23)

The image retrieval process executes the Harbor API and stores the results in the HarborApiArtifact shown below. However, if there are no vulnerability scan results, addition_links.vulnerabilities.href is not included in the return value, which seems to cause the Cannot read properties of undefined (reading 'href') error.

https://github.com/container-registry/backstage-plugin-harbor-backend/blob/ad65cb61fd1deb542e125d371832592afa1d247a/src/service/artifact.ts#L138-L151

This error can be resolved by enabling vulnerability scanning, such as Trivy, on the Harbor side. For more details, refer to Harbor Vulnerability Scanning.

However, even with this fix, there are issues where vulnerability scans on the Harbor side are not correctly retrieved and links to Harbor do not function properly. This is reported in https://github.com/container-registry/backstage-plugin-harbor/issues/272 and has been fixed in the @digitalist-open-cloud/backstage-plugin-harbor plugin used this time.

TechDocs plugin

TechDocs is one of the core features of Backstage, providing a way to build and render Markdown documents using mkdocs for viewing on Backstage. In application development, documentation is required in various situations such as specifications, architecture, operation policies, and hand-over procedures. By using the TechDocs plugin, such documents can be aggregated into the Backstage portal.

Plugin installation and configuration for enabling TechDocs are described at https://backstage.io/docs/features/techdocs/getting-started. However, depending on the Backstage version, it may already be set up during initial construction, so manual configuration may not be necessary. In the version used this time, it was already set up by default.

To associate a Backstage entity with a TechDocs document, you need to specify backstage.io/techdocs-ref: in the entity's annotations. https://backstage.io/docs/features/techdocs/creating-and-publishing

To verify that TechDocs works correctly, create the following files in the Backstage project directory:

.
├── app-config.yml
├── docs
│   └── index.md
├── mkdocs.yml
└── k8s.yml

mkdocs.yml and docs/index.md are the files required to create documentation with MkDocs. Aside from specifying the techdocs-core plugin, you can write them just like you would for any standard MkDocs documentation.

mkdocs.yml
site_name: Backstage-frontend
nav:
  - HomeDir: index.md
plugins:
  - techdocs-core
docs/index.md
## markdown sample

Sample

For k8s.yml, use the same content as the component entity used so far. By specifying the directory path to docs where index.md exists via backstage.io/techdocs-ref: dir:. in the annotations, you can associate the entity with TechDocs.
Due to TechDocs specifications, if you specify a directory above where the file exists, a Relative path is not allowed to refer to a directory outside its parent Relative error will occur. Therefore, temporarily place k8s.yml in the same directory as docs.

k8s.yml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: k8s-example
  annotations:
    backstage.io/kubernetes-label-selector: 'backstage-project=k8s-example'
    argocd/app-name: backstage-sample-app
    janus-idp.io/tekton: k8s-example
    goharbor.io/repository-slug: k8s/backstage-front
+   backstage.io/techdocs-ref: dir:.
spec:
  type: service
  lifecycle: experimental
  owner: guests
  system: examples

Since the location of k8s.yml has changed, also modify app-config.yml.

app-config.yml
catalog:
  locations:
-    - type: file
-      target: ../../examples/k8s.yml
+    - type: file
+      target: ../../k8s.yml

Now, when you start Backstage with yarn dev and look at the overview of the component entity, the View techdocs link will be available.

Clicking this will take you to a page where the content of index.md is rendered by MkDocs (the first time you open the page, it takes a little time because the Markdown is being built). You can also see the same content from the docs tab.

Since generated documents are internally classified as docs, they can also be checked from Docs in the left navigation. This appears to show a list of all doc resources within Backstage.

Because you can create the documentation itself using MkDocs, you can freely include various information such as application descriptions, architecture, and operational policies.

Others

Items that couldn't be summarized above and miscellaneous notes.

Other plugins

While the main part focused on integration examples when using Tekton for CI, the plugin list includes plugins for various other services. Here are some that might be useful:

With monitoring plugins and others, it seems possible to aggregate information such as application monitoring status into Backstage.

Authentication providers

By default, Backstage is not configured with authentication, so anyone who knows the URL can access it without user authentication. However, by specifying an authentication provider, you can implement authentication in collaboration with external services. Major providers such as GitHub and Google are built-in by default, so they can be used without installing additional plugins.

https://backstage.io/docs/auth/

It is also possible to use OIDC providers not in the above list for authentication by implementing OIDC processing.

https://backstage.io/docs/auth/oidc

Running on Kubernetes

Until now, we have been running Backstage locally by executing yarn dev, but when considering full-scale operation, deployment on Kubernetes is recommended.

https://backstage.io/docs/deployment/

At Spotify, we deploy software generally by:

Building a Docker image
Storing the Docker image on a container registry
Referencing the image in a Kubernetes Deployment YAML
Applying that Deployment to a Kubernetes cluster
This method is covered in Building a Docker image and Deploying with Kubernetes.

Deployment on Kubernetes is described in the following documentation.

https://backstage.io/docs/deployment/k8s

Reading through this, it states that the Backstage image should be built according to the following steps.

https://backstage.io/docs/deployment/docker

The build methods for the following configurations are described here. At first glance, Host Build seems to be recommended.

Type Description Merit
Host Build Method where Backstage-related assets are built on the host side and then placed inside the container Build is fast because host-side caching is effective
Multi-stage Build Method using Docker multi-stage builds to build Backstage inside the container Used in some cases
Separate Frontend Method of separating the backend and frontend Used in some cases

Additionally, there is a Helm chart for deploying Backstage.

https://github.com/backstage/charts

While databases, roles, etc., can be set up using the Helm chart, the essential Backstage image itself must be built manually according to the methods mentioned above.

Changing the portal theme

The default theme of the Backstage portal includes two types, dark and light, but you can also create custom themes.

https://backstage.io/docs/getting-started/app-custom-theme/

Additionally, you can use plugins created by others.
I like the Dracula theme, so I searched for a Dracula theme for Backstage and found the following under the dracula organization.

https://github.com/dracula/backstage

Currently, there is no official installation method described, but the installation steps were provided in backstage/plugins/dracula-theme, so I will introduce it by referring to those.

The README says you can install the plugin with yarn --cwd packages/app add @fjudith/plugin-dracula-theme, but since the package doesn't seem to have been uploaded to the npm registry, I will install it from a local source.
First, clone the repository:

git clone https://github.com/dracula/backstage.git

The Dracula theme is located under plugins/dracula-theme, so copy it to the plugins directory of your original Backstage project.

cd backstage
cp -r plugins/dracula-theme [project_dir]/plugins

Then, run yarn add for the local package from the root directory of your original project.

cd [project_dir]
yarn --cwd packages/app add ./plugins/dracula-theme/

After that, add and edit files according to Theme installation and Update logo color.
In the README, the directory is mentioned as packages/app/src/components/, but in my environment, it was in packages/app/src/components/Root.
Also, the following part didn't work as-is and needed to be modified as follows:

packages/app/src/components/Root.tsx
-  path: props => ({
-    fill: props.ThemeId === 'dracula' ? '#F8F8F2' ; '#7df3e1'
-  }),
+  path: props => ({
+    fill: props.themeId === 'dracula' ? '#F8F8F2' : '#7df3e1'
+  }),

-  const themeId = appThemeApi.getActiveThemeId();
+  const appThemeApi = useApi(appThemeApiRef);
+  const themeId = appThemeApi.getActiveThemeId();

When I started Backstage with yarn dev, the following error occurred:

[0] Module parse failed: Unexpected token (12:19)
[0] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[0] |
[0] | // Change stop color: https://johndecember.com/html/spec/colorsvg.html
[0] > export const shapes: Record<string, string> = {
[0] |   wave: `url("data:image/svg+xml,%3csvg xmlns='http://

The error was resolved by uncommenting shapes in the imports and commenting out the original export const shapes section.

plugins/dracula-theme/src/themes/dracula.ts
import {
  createBaseThemeOptions,
  createUnifiedTheme,
  genPageTheme,
  palettes,
+  shapes,
- //  shapes,
} from '@backstage/theme';

import { alpha } from '@material-ui/core/styles';

- // Change stop color: https://johndecember.com/html/spec/colorsvg.html
- // export const shapes: Record<string, string> = {
- //  wave: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='1368'
...

Now, the Dracula theme is applied throughout Backstage.

The theme can be switched from settings > General > Appearance in the bottom left.

Summary

Here is a summary of how the Backstage portal looks when each plugin is enabled.


home page


Overview of the Component entity


Tekton pipeline execution results in the CI/CD tab


In the API tab, API entities associated with the entity are displayed


API definitions written in OpenAPI format are rendered and displayed


The Dependency tab shows the dependencies of the Component


Docs tab


K8s tab


Image list in the Harbor tab


In the System entity, dependencies with other entities are visible at a glance through Relations

The resources used this time are available here.
https://github.com/git-ogawa/zenn_resource/tree/main/articles/backstage

Conclusion

I verified whether CI/CD-related information can be aggregated using Backstage plugins, and it turned out to be organized quite well. In particular, since links to the corresponding web UIs for ArgoCD and Harbor are displayed, you can use the Backstage portal to get a bird's-eye view of the entire project and jump to the specific tool's web UI for more detailed information.
Also, one of the characteristics of Backstage is that you can extend its functionality and usability by writing plugins, mainly in React. However, existing plugins can be applied without diving that deep, making it a significant advantage for those who may not be very familiar with React or frontend development.

Discussion