如何在 Docker 容器内动态添加 Jenkins 用户和权限

2024-04-28

当我为 python 项目构建声明式 Jenkins 管道时,使用 Pip 时收到以下错误消息。

WARNING: The directory '/.cache/pip' or its parent directory is not owned or is not writable by the current user.

My 詹金斯文件:

#!groovy

pipeline {
    agent {
        docker {
            image 'python:3.7.5'
        }
    }

    stages {
        stage('Build Dependencies') {
            steps {
                sh "pip install -r requirements.txt"
            }
        }
}
    post {
        always {
            sh "Job finished"
        }
    }
}

我该如何解决这个问题?


您必须在 Docker 容器中创建一个新定义的用户,而不是使用root用户。您必须使用外域创建新用户GID 和 UID https://medium.com/@gggauravgandhi/uid-user-identifier-and-gid-group-identifier-in-linux-121ea68bf510的参考文献jenkinsJenkins 服务器上的用户。要了解有关 Docker 内部 GID 和 UID 的更多信息,我建议您阅读这篇有趣的文章 https://medium.com/@mccode/understanding-how-uid-and-gid-work-in-docker-containers-c37a01d01cf.

让我们使用 Dockerfile 代理而不是远程映像,这样我们就可以动态分配所需的变量作为构建参数。

首先,我们将获取 jenkins 帐户的外层范围 GID、UID 和用户名:

詹金斯文件:

#!groovy

pipeline {

    environment {
            JENKINS_USER_NAME = "${sh(script:'id -un', returnStdout: true).trim()}"
            JENKINS_USER_ID = "${sh(script:'id -u', returnStdout: true).trim()}"
            JENKINS_GROUP_ID = "${sh(script:'id -g', returnStdout: true).trim()}"
    }
}

现在,我们已将 GID、UID 和用户名分配给管道范围内的各种环境变量。我们现在可以将它们指定为 Dockerfile 的构建参数。

詹金斯文件:

#!groovy

pipeline {

    environment {
            JENKINS_USER_NAME = "${sh(script:'id -un', returnStdout: true).trim()}"
            JENKINS_USER_ID = "${sh(script:'id -u', returnStdout: true).trim()}"
            JENKINS_GROUP_ID = "${sh(script:'id -g', returnStdout: true).trim()}"
    }
    agent {
        dockerfile {
            filename 'Dockerfile.build'
            additionalBuildArgs '''\
            --build-arg GID=$JENKINS_GROUP_ID \
            --build-arg UID=$JENKINS_USER_ID \
            --build-arg UNAME=$JENKINS_USER_NAME \
            '''
        }
    }

    stages {
        stage('Build Dependencies') {
            steps {
                sh "pip install -r requirements.txt"
            }
        }
}
    post {
        always {
            sh "Job finished"
        }
    }
}

最后在 Dockerfile 中我们必须创建定义的用户:

Dockerfile.build

FROM python:3.8.3

ARG GID
ARG UID
ARG UNAME

ENV GROUP_ID=$GID
ENV USER_ID=$UID
ENV USERNAME=$UNAME

RUN mkdir /home/$USERNAME

RUN groupadd -g $GROUP_ID $USERNAME
RUN useradd -r -u $USER_ID -g $USERNAME -d /home/$USERNAME $USERNAME
RUN chown $USERNAME:$USERNAME /home/$USERNAME

USER $USERNAME
WORKDIR /home/$USERNAME

RUN python -m venv testpipe_venv

CMD ["/bin/bash -c 'source testpipe_venv/bin/activate'"]

请注意,我们必须创建一个虚拟 python 环境,因为我们不是root用户不再。在最后的命令中,我们激活虚拟环境以在管道中使用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Docker 容器内动态添加 Jenkins 用户和权限 的相关文章

随机推荐