Jenkins Pipeline如何跨阶段传数据:克隆代码给Kaniko构建使用
Jenkins Pipeline跨阶段传递代码到Kaniko构建阶段的解决方案
以下是两种适配你场景的可行方案:
方案1:使用stash/unstash内置能力(适用于代码体积≤500M的场景)
Jenkins内置的stash/unstash是专门用于跨阶段传递文件的能力,不受阶段agent差异影响,实现逻辑如下:
- 代码克隆阶段完成拉取后,将仓库所有文件暂存到Jenkins控制器
- 镜像构建阶段启动Kaniko容器后,先拉取暂存的文件到当前工作目录,再执行构建
修改后的Pipeline示例:
pipeline { agent none stages { stage('Clone repository') { agent { label 'builder' } steps { sh 'git clone ssh://git@myrepo.com./repo.git' // 暂存repo目录下的所有文件,自定义stash名称为repo-code stash name: 'repo-code', includes: 'repo/**' } } stage('Build application') { agent { docker { label 'builder' image 'gcr.io/kaniko-project/executor:debug' args '-u 0 --entrypoint=""' } } steps { // 拉取之前暂存的代码到当前工作目录 unstash 'repo-code' sh '''#!/busybox/sh /kaniko/executor -c ./repo -f ./repo/Dockerfile ''' } } } }
如果不需要保留.git目录,可以在stash参数中加excludes: 'repo/.git/**'减少打包传输的体积。
方案2:同节点工作区挂载(适用于大体积代码仓库,性能更优)
由于你的两个阶段都调度到带有builder标签的同一节点,可以直接将宿主机节点的工作区目录挂载到Kaniko容器内,不需要打包传输,性能更高。
修改后的Pipeline示例:
pipeline { agent none stages { stage('Clone repository') { agent { label 'builder' } steps { sh 'git clone ssh://git@myrepo.com./repo.git' } } stage('Build application') { agent { docker { label 'builder' image 'gcr.io/kaniko-project/executor:debug' // 挂载宿主机当前工作目录到容器内的/workspace目录 args '-u 0 --entrypoint="" -v ${WORKSPACE}:/workspace' } } steps { sh '''#!/busybox/sh /kaniko/executor -c /workspace/repo -f /workspace/repo/Dockerfile ''' } } } }
Dockerfile适配说明
你当前使用的ADD . /片段不需要修改,只要Kaniko的-c参数指定到仓库根目录,就可以正确将所有代码文件拷贝到镜像的根目录。
内容的提问来源于stack exchange,提问作者Manish Iarhovich
相关产品推荐
相关产品推荐

