Bootstrap

jenkins pipeline流水线构建使用

文章目录

  • 非交互性修改k8s 资源对象yml 中镜像的shell 脚本
cat /data/k8s_token_auth/update_deploy_info.sh
#/bin/bash
yaml_file=$1
sed -i -e '/^status:/,$d' -e '/resourceVersion/,+2d'  ${yaml_file}

声明式

  • 使用jenkins 全局工具中配置的node 环境案例
pipeline {
    agent { node { label "${build_host_label}" } }
    tools {
        //工具名称必须在Jenkins 管理Jenkins → 全局工具配置中预配置。
        nodejs  'node-prod'
    }
    stages {
        stage('查看node环境是否已安装好') {
            steps {
                sh 'node  -v'
              }
        }
    }
}
  • 通过jenkins参数化构建实现对k8s 实现单个服务的发布,回滚,重启操作
    当action 参数为deploy 时发布,为rollout 时,回退到上一个版本,为restart 时重启服务。
	pipeline {
	agent none
	environment { 
        branch = 'release/prod'       //gitlab 代码分支
		codeGroup = 'codegroup'             //git 代码组
        codeName='post'	  //微服务代码仓库名字
		registryNamespace = "registryNamespace "  
		imageName = "post"   //容器镜像名字
		deployName = "post"  //k8s deployment 名字
		namespace = 'backend'
		kubectl_cmd = "kubectl --kubeconfig=${ukiKubeconfigPath}"   //k8s 的 api 认证
		//部分全局变量配置在jenkins 的管理页面
    }
	
    options { 
	   timestamps()  //打印执行步骤的时间戳
	   timeout(time: 1,unit: 'HOURS')  //流水线任务超时设置1h
	   buildDiscarder(logRotator(numToKeepStr: '10')) //保留最大的构建记录数
	   disableConcurrentBuilds()  //禁止并行
	   }

	stages {
		stage('自动获取镜像版本号新增'){
		    agent { node { label "${deploy_host_lable}"} }
		    when {
                expression { 
                   return  (action == 'deploy' )
                }
            }
		    steps {
			  script {
			     int runingVersion = sh(
							label: '',
							returnStdout: true,
							script: "${kubectl_cmd} get deployment  ${deployName} -n ${namespace} -o yaml  | grep ${filterversion}| tail -n 1 | awk -F ':'  '{print \$NF}'"
				            ).trim()
				   echo "线上正在运行的版本:${runingVersion}"
				   version =  (runingVersion + 1)
				   echo "本次将要发布使用的版本号:${version}"
				   
				   if (runingVersion == "${version}" || runingVersion == "" ){
				         error("输入镜像版本与线上正在运行的版本冲突或者没有获取到该对象资源deployment/${deployName}") //主动终止整个pipeline 
				   }
				}
			}
		}
		stage('拉取代码') {
		    agent { node { label "${build_host_label}" } }
		    when {
                expression { 
                   return  (action == 'deploy' )
                }
            }
			steps {
                checkout([
                    $class: 'GitSCM', 
                    branches: [[name: "${branch}"]], 
                    doGenerateSubmoduleConfigurations: false, 
                    extensions: [], submoduleCfg: [], 
                    userRemoteConfigs: [[
                        credentialsId: "${gitlabCredentialsId}", url: "${gitlabUrl}:${codeGroup}/${codeName}.git"
						]]
                    ])
                }
			}
		
		stage('build and push image') {
		    agent { node { label "${build_host_label}" } }
		    when {
                expression { 
                   return  (action == 'deploy' )
                }
            }
			steps {
			     sh "docker login --username=${dockerUser} -p ${dockerPasswd} ${baseRegistryUrl}"
                 sh "echo '更新基础镜像' && sh /data/devops/shell/k8s-tools/build_pre_hook.sh || /bin/true"
			     sh "docker build   --no-cache    -t ${baseRegistryUrl}/${registryNamespace}/${imageName}:${version} ."
			     sh "docker push ${baseRegistryUrl}/${registryNamespace}/${imageName}:${version}"     
            }    
		}
		
		stage('发布') {
		    agent { node { label "${deploy_host_lable}"} }
		    when {
                expression { 
                   return  (action == 'deploy' )
                }
            }
			steps {
				sh "${kubectl_cmd} get deploy  ${deployName}  -n ${namespace} -o yaml > ${deployName}.yaml "
				sh "sh /data/devops/shell/k8s-tools/update_deploy_info.sh  ${version} ${deployName}.yaml"
                sh "${kubectl_cmd} apply  -f ./${deployName}.yaml"
                sh "${kubectl_cmd}  rollout status deployment ${deployName} -n ${namespace}"
			}
		}
	stage('回滚') {
		    agent { node { label "${deploy_host_lable}"} }
		    when {
                expression { 
                   return  (action == 'rollout' )
                }
            }
			steps {
				sh "${kubectl_cmd}  rollout undo deployment ${deployName} -n ${namespace}"
			}
		}
		stage('重启服务') {
		    agent { node { label "${deploy_host_lable}"} }
		    when {
                expression { 
                   return  (action == 'restart' )
                }
            }
			steps {
				sh "${kubectl_cmd}  rollout restart deployment ${deployName} -n ${namespace}"
			}
		}
	}
}

脚本式

node("test-dev"){
    stage("清理数据test-dev") {
        sh "docker images | awk '{print \$3}'  | xargs docker rmi || /bin/true"
    }
}
node("cn-build"){
    stage("清理数据cn-build") {
        sh "docker images | awk '{print \$3}'  | xargs docker rmi || /bin/true"
    }
}
;