一. 基于GitLab的WebHooks
这里要实现自动化的一个CI操作,也就是开发人员Push代码到Git仓库后,Jenkins会自动的构建项目,将最新的提交点代码构建并进行打包部署,这里区别去上述的CD操作,CD操作需要基于某个版本进行部署,而这里每次都是将最新的提交点集成到主干上并测试。
1.1 WebHooks通知
开启Jenkins的自动构建:
构建触发器
设置Gitlab的Webhooks:
设置Gitlab的Webhooks
需要关闭Jenkins的Gitlab认证:
关闭Jenkins的Gitlab认证
再次测试Gitlab:
再次测试
1.2 修改配置
修改Jenkinsfile实现基于最新提交点实现持续集成效果,将之前引用${tag}的全部去掉:
// 所有的脚本命令都放在pipeline中 pipeline{ // 指定任务再哪个集群节点中执行 agent any // 声明全局变量,方便后面使用 environment { harborUser = 'admin' harborPasswd = 'Harbor12345' harborAddress = '192.168.11.102:80' harborRepo = 'repo' } stages { stage('拉取git仓库代码') { steps { checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: 'http://192.168.11.101:8929/root/mytest.git']]]) } } stage('通过maven构建项目') { steps { sh '/var/jenkins_home/maven/bin/mvn clean package -DskipTests' } } stage('通过SonarQube做代码质量检测') { steps { sh '/var/jenkins_home/sonar-scanner/bin/sonar-scanner -Dsonar.source=./ -Dsonar.projectname=${JOB_NAME} -Dsonar.projectKey=${JOB_NAME} -Dsonar.java.binaries=./target/ -Dsonar.login=40306ae8ea69a4792df2ceb4d9d25fe8a6ab1701' } } stage('通过Docker制作自定义镜像') { steps { sh '''mv ./target/*.jar ./docker/ docker build -t ${JOB_NAME}:latest ./docker/''' } } stage('将自定义镜像推送到Harbor') { steps { sh '''docker login -u ${harborUser} -p ${harborPasswd} ${harborAddress} docker tag ${JOB_NAME}:latest ${harborAddress}/${harborRepo}/${JOB_NAME}:latest docker push ${harborAddress}/${harborRepo}/${JOB_NAME}:latest ''' } } stage('将yml文件传到k8s-master上') { steps { sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'pipeline.yml')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)]) } } stage('远程执行k8s-master的kubectl命令') { steps { sh '''ssh root@192.168.11.201 kubectl apply -f /usr/local/k8s/pipeline.yml ssh root@192.168.11.201 kubectl rollout restart deployment pipeline -n test''' } } } post { success { dingtalk( robot: 'Jenkins-DingDing', type: 'MARKDOWN', title: "success: ${JOB_NAME}", text: ["- 成功构建:${JOB_NAME}! \n- 版本:latest \n- 持续时间:${currentBuild.durationString}" ] ) } failure { dingtalk( robot: 'Jenkins-DingDing', type: 'MARKDOWN', title: "success: ${JOB_NAME}", text: ["- 构建失败:${JOB_NAME}! \n- 版本:latest \n- 持续时间:${currentBuild.durationString}" ] ) } } }
修改pipeline.yml,更改镜像版本:
apiVersion: apps/v1 kind: Deployment metadata: namespace: test name: pipeline labels: app: pipeline spec: replicas: 2 selector: matchLabels: app: pipeline template: metadata: labels: app: pipeline spec: containers: - name: pipeline image: 192.168.11.102:80/repo/pipeline:latest # 这里 imagePullPolicy: Always ports: - containerPort: 8080 # 省略其他内容…………
1.3 滚动更新
因为pipeline没有改变时,每次不会重新加载,这样会导致Pod中的容器不会动态更新,这里需要使用kubectl的rollout restart命令滚动更新
设置Jenkinsfle