在昨天簡單介紹完 Docker Pipeline 後我們來重新改寫 Jenkinsfile。
pipeline{
agent {
label 'gcp-agent-1'
}
environment {
IMAGE_REFERENCE = "docker.pkg.github.com/ben4932042/ithome-crawler/scrapy:${env.BRANCH_NAME}"
}
stages{
stage("Setup registry auth"){
steps{
withCredentials([usernamePassword(credentialsId: 'github-registry-secret', usernameVariable: 'USER', passwordVariable: 'TOKEN')]){
script{
sh "docker login docker.pkg.github.com -u ${USER} -p ${TOKEN}"
}
}
}
}
stage("build and test the project") {
agent {
docker {
image "python:3.7-slim"
args '-u root'
}
}
stages {
stage("Setup requirements") {
steps {
sh """
pip3 install -r requirements.txt
pip3 install pylint
pip3 install pytest
"""
}
}
stage("Lint") {
steps{
sh """
export PYTHONPATH=${WORKSPACE}
pylint --fail-under=10 src
"""
}
}
stage("Test") {
steps {
sh """
export PYTHONPATH=${WORKSPACE}
pytest tests
"""
}
}
}
}
stage("Build"){
when {
branch "main"
}
steps{
sh "docker build -t ${IMAGE_REFERENCE} ."
}
}
stage("Push"){
when {
branch "main"
}
steps{
sh "docker push ${IMAGE_REFERENCE}"
}
}
}
post{
always{
cleanWs()
}
}
}
我們用 docker agent 取代本來的 virtualenv 的部分,當我們需要做 python 版本更動時,只需要修改 Dockerfile 以及 Jenkinsfile 中 docker agent 的版本號即可。
需要特別注意,在 docker pipeline 執行時,在 container 內登入的 User ID 為 1000 而不是 root,故如有碰到需要在 docker 安裝套件時等需要 sudo
的需求時,可以有以下兩種方式:
agent { dockerfile true }
agent {
docker {
image "python:3.7-slim"
args '-u root'
}
}
https://github.com/ben4932042/ithome-crawler
https://issues.jenkins.io/browse/JENKINS-54408
https://www.jenkins.io/doc/book/pipeline/docker/