如何使用 jenkins pipline 步骤在 docker 镜像中安装 pip ?

tia*_*lva 8 jenkins docker jenkins-pipeline

我有这个Dockerfile

FROM python:3.7

CMD ["/bin/bash"]
Run Code Online (Sandbox Code Playgroud)

和这个Jenkinsfile

pipeline {
agent {
    dockerfile {
        filename 'Dockerfile'
    }
}
stages {
    stage('Install') {
        steps {
            sh 'pip install --upgrade pip'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

The directory '/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
Installing collected packages: pip
  Found existing installation: pip 19.0.2
Uninstalling pip-19.0.2:
Could not install packages due to an EnvironmentError: [Errno 13] 
Permission denied: '/usr/local/bin/pip'
Consider using the `--user` option or check the permissions.
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用--user,但没有成功。

我在--user 0:0docker jenkinsfile 声明中使用 args 很幸运,但这会创建 root 拥有的目录和文件,用户 Jenkins 在下次运行时无法删除这些目录和文件。

我不想pip install在 Dockerfile 上执行该操作,因为实际上安装步骤正在运行一个 make 文件,而不是我上面使用的简化,我想在其他上下文中使用它。

我也看到了意见改变HOME environment var,这似乎解决了第2个警告关于不被当前用户所拥有的父directoy,而不是Errno 13一部分。

hoe*_*ing 4

正如我在此评论中提到的,解决方案应该是在容器内添加适当的用户。Jenkins984:984在我的机器上使用 uid/gid (但在你的机器上可能有所不同 - 登录到运行 Jenkins 的主机并执行sudo -u jenkins id -a以检测它们),因此您需要将其复制到应由 Jenkins 运行的容器中:

FROM python:3.7

RUN mkdir /home/jenkins
RUN groupadd -g 984 jenkins
RUN useradd -r -u 984 -g jenkins -d /home/jenkins jenkins
RUN chown jenkins:jenkins /home/jenkins
USER jenkins
WORKDIR /home/jenkins

CMD ["/bin/bash"]
Run Code Online (Sandbox Code Playgroud)

当然,由于您不再是root容器中的用户,因此要么创建一个虚拟环境:

$ docker run --rm -it jenkins/python /bin/bash
jenkins@d0dc87c39810:~$ python -m venv myenv
jenkins@d0dc87c39810:~$ source myenv/bin/activate
jenkins@d0dc87c39810:~$ pip install numpy
Run Code Online (Sandbox Code Playgroud)

或使用--user参数:

$ docker run --rm -it jenkins/python /bin/bash
jenkins@d0dc87c39810:~$ pip install --user --upgrade pip
jenkins@d0dc87c39810:~$ pip install --user numpy
Run Code Online (Sandbox Code Playgroud)

ETC。


或者,您可以(但在大多数情况下不应该)将容器输入为root,但使用jenkins组:

$ docker run --user 0:984 ...
Run Code Online (Sandbox Code Playgroud)

这样,虽然修改的文件仍然会改变所有者,但它们的组所有权仍然完好无损,因此 Jenkins 将能够清理文件(或者你可以自己做,通过

sh 'rm -f modified_file'
Run Code Online (Sandbox Code Playgroud)

在里面Jenkinsfile