第 6 章 以非 root 用户身份使用 Buildah 构建容器镜像
作为 root 用户在容器上运行 OpenShift Pipelines,可以将容器进程和主机公开给其他潜在的恶意资源。您可以作为容器中的特定非 root 用户运行工作负载来降低此类风险。
在大多数情况下,您可以通过创建一个自定义任务来构建镜像并在此任务中配置用户命名空间,可以在没有 root 权限的情况下运行 Buildah。
如果您的镜像没有成功使用此配置构建,您可以使用自定义服务帐户(SA)和安全上下文约束(SCC)定义;但是,如果使用此选项,则必须启用 Buildah 步骤来提升其权限(allowPrivilegeEscalation: true
)。
6.1. 通过配置用户命名空间,以非 root 用户身份运行 Buildah
配置用户命名空间是以非 root 用户身份在任务中运行 Buildah 的最简单方法。但是,一些镜像可能无法使用这个选项进行构建。
先决条件
-
已安装
oc
命令行工具。
流程
要创建
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 -
输入以下命令编辑复制的
buildah
任务:$ oc edit task buildah-as-user
在新任务中,创建
annotations
和stepTemplate
部分,如下例所示:在
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
。
-
使用新的
buildah-as-user
任务在管道中构建镜像。