第 6 章 以非 root 用户身份使用 Buildah 构建容器镜像


作为 root 用户在容器上运行 OpenShift Pipelines,可以将容器进程和主机公开给其他潜在的恶意资源。您可以作为容器中的特定非 root 用户运行工作负载来降低此类风险。

在大多数情况下,您可以通过创建一个自定义任务来构建镜像并在此任务中配置用户命名空间,可以在没有 root 权限的情况下运行 Buildah。

如果您的镜像没有成功使用此配置构建,您可以使用自定义服务帐户(SA)和安全上下文约束(SCC)定义;但是,如果使用此选项,则必须启用 Buildah 步骤来提升其权限(allowPrivilegeEscalation: true)。

6.1. 通过配置用户命名空间,以非 root 用户身份运行 Buildah

配置用户命名空间是以非 root 用户身份在任务中运行 Buildah 的最简单方法。但是,一些镜像可能无法使用这个选项进行构建。

先决条件

  • 已安装 oc 命令行工具。

流程

  1. 要创建 openshift-pipelines 命名空间中提供的 buildah 任务的副本,并将副本的名称改为 buildah-as-user,请输入以下命令:

    $ oc get task buildah -n openshift-pipelines -o yaml | yq '. |= (del .metadata |= with_entries(select(.key == "name" )))' | yq '.kind="Task"' | yq '.metadata.name="buildah-as-user"' | oc create -f -
  2. 输入以下命令编辑复制的 buildah 任务:

    $ oc edit task buildah-as-user

    在新任务中,创建 annotationsstepTemplate 部分,如下例所示:

    buildah-as-user 任务中添加示例

    apiVersion: tekton.dev/v1
    kind: Task
    metadata:
      annotations:
        io.kubernetes.cri-o.userns-mode: 'auto:size=65536;map-to-root=true'
        io.openshift.builder: 'true'
      name: assemble-containerimage
      namespace: pipeline-namespace
    spec:
      description: This cluster task builds an image.
    #  ...
      stepTemplate:
        env:
          - name: HOME
            value: /tekton/home
        image: $(params.builder-image)
        imagePullPolicy: IfNotPresent
        name: ''
        resources:
          limits:
            cpu: '1'
            memory: 4Gi
          requests:
            cpu: 100m
            memory: 2Gi
        securityContext:
          capabilities:
            add:
              - SETFCAP
          runAsNonRoot: true
          runAsUser: 1000 1
        workingDir: $(workspaces.working-directory.path)
    #  ...

    1
    runAsUser: 设置没有严格必要,因为使用了 podTemplate
  3. 使用新的 buildah-as-user 任务在管道中构建镜像。
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.