jenkins+k8s+pipeline
使用jenkinsfile持续集成Django项目
1,kubeadm部署k8s集群,集群内部署jenkins,jenkins安装kubernets plugin插件,
2,使用jenkinsfile实现自动拉代码,自动编译,自动构建docker镜像,推送镜像到harbor,更改yaml文件部署应用
#podtemplate定义jenkins-slave容器模板,label标签,serveraccount是k8s集群rbac账号,
podTemplate(label: 'test',serverAccout: 'jenkins-sa', securityContext: [ runAsUser: 'root'],
#jnlp容器镜像默认以jenkins用户运行,这样会导致在jnlp容器内执行docker命令时,会有权限问题,因为jnlp容器挂载了宿主机的docker.sock,
#宿主机的docker.sock权限是660,所以jnlp容器执行不了,简单解决方式可以自定义Dockerfile生成jnlp镜像,使用USER root将镜像默认运行的用户改为root containers: [ containerTemplate(name: 'jnlp', image: '192.168.125.202/image/jenkins_inbound_agent:v1', args: '${computer.jnlpmac} ${computer.name}'), ],
#将宿主机docker.sock,docker跟libltdl.so.7挂载进容器内,让容器可以执行docker命令,docker in docker
#k8s定义一个pvc,挂载一个文件夹进去,保存git代码 volumes: [ hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'), hostPathVolume(hostPath: '/usr/bin/docker', mountPath: '/usr/bin/docker'), hostPathVolume(hostPath: '/usr/lib64/libltdl.so.7', mountPath: '/usr/lib/x86_64-linux-gnu/libltdl.so.7'), persistentVolumeClaim(claimName: 'test', mountPath: '/opt/code', readOnly: false) ], ) {
node('test') {
#定义变量
def app_name='learn_logs'
def workdir='/home/jenkins/'
def img_url='192.168.125.202'
def docker='/usr/bin/docker'
stage('Clone') {
echo "1.Clone Stage"
sh "${workdir}kubectl --kubeconfig ${workdir}.kube/config get pods -n devops"
sh "cd ${workdir}learn_logs && git pull origin master"
}
stage('Test') {
echo "2.Test Stage"
#获取项目最近一次提交的commit id,并注册到env中去,用以构建镜像的版本号
script {
env.imageTag = sh (script: 'GIT_DIR=/home/jenkins/learn_logs/.git git rev-parse --short HEAD ${GIT_COMMIT}', returnStdout: true).trim()
env.img_url_all = "${img_url}/image/${app_name}:${imageTag}"
}
sh "echo ${imageTag}"
sh "echo ${img_url_all}"
}
stage('Build') {
echo "3.Build Docker Image Stage."
sh "cd ${workdir}${app_name} && ${docker} build -t ${img_url}/image/${app_name}:${imageTag} -f ${workdir}${app_name}/Dockerfile /home"
}
stage('Push') {
echo "4.Push Docker Image Stage."
#使用函数withcredentials获取jenkins上面的账号信息,用以登录镜像仓库
withCredentials([usernamePassword(credentialsId: 'harbor_user', passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME')]) {
sh "docker login ${img_url}/harbor -u $USERNAME -p $PASSWORD"
sh "/usr/bin/docker push ${img_url}/image/${app_name}:${imageTag}"
}
}
stage('YAML') {
echo "5. Change YAML File Stage."
#替换yaml文件镜像名称
//def img_url_all="192.168.125.202/image/learnlog:${imageTag}"
sh "sed -i 's#{{img}}#${img_url_all}#g' ${workdir}${app_name}/${app_name}.yaml"
}
stage('Deploy') {
echo "6. Deploy Stage."
//def img_url_all="192.168.125.202/image/learnlog:${imageTag}"
sh "${workdir}kubectl --kubeconfig ${workdir}.kube/config apply -f ${workdir}${app_name}/${app_name}.yaml"
#执行完再讲yaml文件镜像名称改成通用匹配字符
sh "sed -i 's#${img_url_all}#{{img}}#g' ${workdir}${app_name}/${app_name}.yaml"
}
}
}