Skip to content

插件制作

在 云原生构建 中,一个插件就是一个 Docker 镜像。下面介绍如何使用 Bash 从零开发一个镜像插件。 本示例插件的功能是打印 hello world,假设您已了解 Docker 基本知识。

设计插件

参数设计

设计插件参数:

  • text: 要输出到控制台的文本内容
yaml
# .cnb.yml
main:
  push:
    - stages:
        - name: hello world
          image: cnbcool/hello-world
          settings:
            text: hello world

这些参数会以环境变量的形式传入容器,并转换为大写且添加 PLUGIN_ 前缀。 上述参数会转化为如下环境变量: PLUGIN_TEXT="hello world"

支持的参数类型

参数类型支持字符串、数值、布尔值、一维数组、普通对象 其中:

  • 数组传给容器时以英文逗号 , 分隔
  • 普通对象传给容器时会转为 JSON 字符串

如果参数值过于复杂,可存放到文件中由插件运行时加载,或简化参数设计、拆分为多个插件。

yaml
# .cnb.yml
main:
  push:
    - stages:
        - name: hello world
          image: cnbcool/hello-world
          settings:
            boolean: true
            number: 123
            array: [hello, world]
            map:
              key: value

对应环境变量:

PLUGIN_BOOLEAN='true'
PLUGIN_NUMBER='123'
PLUGIN_ARRAY='hello,world'
PLUGIN_MAP='{"key":"value"}'

书写脚本

下一步编写一个打印参数的 Bash 脚本:

sh
#!/bin/sh
echo "$PLUGIN_TEXT"

构建插件镜像

插件会打包成 Docker 镜像分发使用。需要创建一个 Dockerfile 将脚本打包进去,并设置为 Entrypoint。

dockerfile
FROM alpine

ADD entrypoint.sh /bin/
RUN chmod +x /bin/entrypoint.sh

ENTRYPOINT /bin/entrypoint.sh

构建镜像:

sh
docker build -t cnbcool/hello-world .

测试插件

建议在本地测试好插件,可使用 docker run 运行插件,通过环境变量传入参数:

sh
docker run --rm \
-e PLUGIN_TEXT="hello world" \
cnbcool/hello-world

测试文件系统访问

插件可以读取构建流程工作区目录,默认将构建目录映射到插件的某个目录并设置为工作区:

sh
docker run --rm \
-e PLUGIN_TEXT="hello world" \
-v $(pwd):$(pwd) \
-w $(pwd) \
cnbcool/hello-world

导出变量

如果插件执行完后,需要返回结果并导出为变量供后续任务使用,可以参考 exports。

发布插件

插件是一个 Docker 镜像,发布插件即发布镜像。 可发布到云原生构建仓库自带的制品库,也可发布到 Docker Hub 以供全球使用。

发布镜像

sh
docker push cnbcool/hello-world