如何在Jenkins中为pip install传递Artifactory或SSH凭证以完成依赖安装
如何在Jenkins中为pip install传递Artifactory或SSH凭证以完成依赖安装
我来给你分享两种场景下的具体操作方法,都是在Jenkins流水线里亲测可行的:
一、给pip传递Artifactory凭证的方法
这里有两种实用方案,按需选就行:
直接把凭证嵌入pip源URL
先在Jenkins的凭证管理里存好你的Artifactory用户名和密码(选「用户名和密码」类型),然后在流水线脚本里用credentials()方法取出,拼到pip的源地址里。示例代码如下:pipeline { agent any environment { // 替换成你在Jenkins中保存的凭证ID ARTIFACTORY_CREDS = credentials('your-artifactory-cred-id') ARTIFACTORY_PIP_URL = "https://${ARTIFACTORY_CREDS_USR}:${ARTIFACTORY_CREDS_PSW}@your-artifactory-domain.com/artifactory/api/pypi/your-pypi-repo/simple/" } stages { stage('Install Dependencies') { steps { sh 'pip install your-package --index-url ${ARTIFACTORY_PIP_URL}' } } } }这样pip安装时会自动使用带凭证的源,完全不用手动输入。
用pip配置文件临时注入凭证
要是觉得把凭证写在URL里不够优雅,可以临时生成pip的配置文件,把凭证和源信息写进去。流水线里可以这么做:pipeline { agent any environment { ARTIFACTORY_CREDS = credentials('your-artifactory-cred-id') } stages { stage('Set Up Pip Config') { steps { sh ''' mkdir -p ~/.config/pip cat > ~/.config/pip/pip.conf << EOF [global] index-url = https://your-artifactory-domain.com/artifactory/api/pypi/your-pypi-repo/simple/ [install] trusted-host = your-artifactory-domain.com [netrc] machine your-artifactory-domain.com login ${ARTIFACTORY_CREDS_USR} password ${ARTIFACTORY_CREDS_PSW} EOF ''' } } stage('Install Dependencies') { steps { sh 'pip install your-package' } } } }这个方法更干净,后续所有pip命令都会自动读取这个配置。
二、给pip传递SSH凭证安装Git仓库依赖
如果是通过git+ssh://方式从Git仓库安装依赖,核心是让Jenkins的代理节点能通过SSH认证访问Git仓库,推荐两种方法:
用Jenkins的SSH凭证+ssh-agent插件
先在Jenkins里存好SSH私钥凭证(选「SSH Username with private key」类型),然后用ssh-agent插件把私钥加载到代理节点的SSH环境中。示例流水线代码:pipeline { agent any stages { stage('Install from Git via SSH') { steps { // 替换成你的SSH凭证ID sshagent(['your-ssh-cred-id']) { sh 'pip install git+ssh://git@your-git-domain.com/your-repo.git@your-branch' } } } } }ssh-agent会自动处理私钥的加载,pip调用Git时就能自动完成认证了。
临时配置Git的凭证助手
要是不想用ssh-agent,也可以临时设置Git的凭证助手,把用户名和token/密码传进去(适合HTTPS地址的Git仓库,也能适配SSH场景):pipeline { agent any environment { // 这里保存的是Git用户名和token/密码凭证 GIT_CREDS = credentials('your-git-cred-id') } stages { stage('Install from Git') { steps { sh ''' git config --global credential.helper '!f() { echo "username=${GIT_CREDS_USR}"; echo "password=${GIT_CREDS_PSW}"; }; f' pip install git+https://your-git-domain.com/your-repo.git@your-branch ''' } } } }
备注:内容来源于stack exchange,提问作者xaviersjs
相关产品推荐
相关产品推荐

