在Backstage中集成Harbor

在Backstage中集成Harbor

Zave Genshin Impact

注意
本文档基于 Backstage 1.32.0 版本编写,并采用自 1.24.0 版本以来官方推荐使用的新后端系统(New BackEnd System)。Backstage 仍处于不断更新发展中,本文下述步骤可能将不适用于后续更新版本。

一、开发前准备

  1. 确认 Harbor 能够和 ArgoCD 互相 ping 通
  2. 确认 Harbor 能够和 Jenkins 互相 ping 通
  3. Harbor 与 Azure 集成完成,能够使用 Azure 账号登录 Harbor
  4. 开发参考文档:

二、创建自定义操作脚手架用于为项目在 Harbor 中创建指定 Project

Harbor 在 Backstage 插件市场中存在一个成熟的插件,可以在前端进行展示相关数据。但是根据本 Backstage 开发项目的需求,Harbor 的作用仅仅只是需要制作和发布镜像,因此此处将不再包含前后端集成的操作。

若有需要,此处额外给出相关参考文档:Harbor | Backstage 集成说明文档

(1)编写操作脚手架业务逻辑

新建 harbor.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import { createTemplateAction } from '@backstage/plugin-scaffolder-node';
import myCache from '../../../../packages/global/node-cache';

export function createExampleAction() {
// For more information on how to define custom actions, see
// https://backstage.io/docs/features/software-templates/writing-custom-actions
return createTemplateAction<{
Harbor_project_name: string;
GitLab_Username: string;
}>({
id: 'acme:harbor:create',
description: 'create harbor project',
schema: {
input: {
type: 'object',
required: ['Harbor_project_name', 'GitLab_Username'],
properties: {
Harbor_project_name: {
title: 'Harbor project name',
description: 'Harbor project name',
type: 'string',
},
GitLab_Username: {
title: 'GitLab Username',
description: 'GitLab Username',
type: 'string',
},
},
},
},
async handler(ctx) {
const harbor_project_name = ctx.input.Harbor_project_name;
const HARBOR_BASE_URL = 'https://harbor.xxxxxx.com.cn';
const admin_Token_Base64 =
'xxxxxxxxxxxxxxxxxx';
let projectExists = false;

const tenantId: string = 'xxxxxxxxxx';
const client_id = 'xxxxxxxxx';
const client_secret = 'xxxxxxxxxx';
const MICROSOFT_LOGIN_BASE_URL =
`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
const username = ctx.input.GitLab_Username.toLocaleLowerCase();

let refresh_Token: string | undefined = myCache.get(`${username}_refreshToken`);
let id_token = "";

// 查询项目是否存在
try {
// 使用admin账号操作就无需使用CSRF
const response = await fetch(
`${HARBOR_BASE_URL}/api/v2.0/projects/${harbor_project_name}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${admin_Token_Base64}`
}
}
);
// 存在会返回200,不存在会返回401等
if (response.status === 200) {
projectExists = true;
}
} catch (error) {
ctx.logger.error('Error get Harbor Project:', error);
throw error;
}

// 不存在项目时创建项目,存在则跳过
if (!projectExists) {
// 先获取id_token
try {
const params = new URLSearchParams({
client_id: client_id,
client_secret: client_secret,
redirect_uri: 'https://harbor.xxxxxx.com.cn/c/oidc/callback',
grant_type: 'refresh_token',
scope: 'openid profile offline_access'
});

if (refresh_Token) {
params.append('refresh_token', refresh_Token);
}

const response_microsoft = await fetch(`${MICROSOFT_LOGIN_BASE_URL}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString()
});

if (!response_microsoft.ok) {
throw new Error(`Fail to connect to Microsoft login site, Status: ${response_microsoft.status}`);
}

const data = await response_microsoft.json();
id_token = data.id_token;
refresh_Token = data.refresh_token;
myCache.set(`${username}_refreshToken`, refresh_Token, 0);
} catch (error) {
ctx.logger.error('Error connect to Microsoft login site:', error);
throw error;
}

// 通过获取的id_token创建project
try {
// 先要获取CSRF_Token
const response_csrf = await fetch(`${HARBOR_BASE_URL}/c/login`, {
method: 'GET',
});
const X_Harbor_Csrf_Token = response_csrf.headers.get('X-Harbor-Csrf-Token');

// 再进行创建
const body = {
project_name: ctx.input.Harbor_project_name,
public: false
};

const response_harbor = await fetch(`${HARBOR_BASE_URL}/api/v2.0/projects`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${id_token}`,
'Content-Type': 'application/json',
'X-Harbor-Csrf-Token': `${X_Harbor_Csrf_Token}`
},
body: JSON.stringify(body)
});

if (response_harbor.status !== 201) {
throw new Error('Fail to create Harbor project.');
}
} catch (error) {
ctx.logger.error('Error to create Harbor project.:', error);
throw error;
}
}
},
});
}

在这里的例子中,走通的逻辑是:首先根据创建项目时填写的指定 Harbor Project 的信息,查找 Harbor 服务器中是否已经存在了这个项目,如果存在就跳过,不存在的话就会执行在 Harbor 中创建该名称命名的 Project。当然,创建的这个 Project 的所有人是当前执行这个程序的登录账号,并且将设置仓库为私有。由于 Harbor 也存在 CSRF 机制,因此我们除了需要获取用户 Azure 认证信息以外,我们也需要通过访问一次登录接口获取 X-Harbor-Csrf-Token 的值,来规避 CSRF 检查。

如果后续还需要有其他的需求,也可以按照上面的逻辑,参照 Harbor REST API V2.0 的文档 进一步开发。

(2)修改其他文件

新建 module.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { createBackendModule } from "@backstage/backend-plugin-api";
import { scaffolderActionsExtensionPoint } from '@backstage/plugin-scaffolder-node/alpha';
import { createExampleAction } from "./actions/harbor";

/**
* A backend module that registers the action into the scaffolder
*/
export const HarborScaffolderModule = createBackendModule({
moduleId: 'harbor-create-project',
pluginId: 'scaffolder',
register({ registerInit }) {
registerInit({
deps: {
scaffolderActions: scaffolderActionsExtensionPoint
},
async init({ scaffolderActions }) {
scaffolderActions.addActions(createExampleAction());
},
});
},
});

新建 index.ts:

1
export { HarborScaffolderModule as default } from './module';

三、如何调用自定义操作脚手架

在软件模板的步骤中添加:

1
2
3
4
5
6
- id: create-harbor
name: Create Harbor Project
action: acme:harbor:create
input:
Harbor_project_name: ${{ parameters.Harbor_project_name }}
GitLab_Username: ${{ parameters.GitLab_Username }}

通过上述内容,在创建项目时,将会在 Harbor 服务器中检查并创建指定命名的 Harbor Project。

  • 标题: 在Backstage中集成Harbor
  • 作者: Zave
  • 创建于 : 2026-09-05 12:00:00
  • 更新于 : 2026-09-05 12:00:00
  • 链接: https://zavex.cn/post/17222.html
  • 版权声明: 版权所有 © Zave,禁止转载。
评论