Jenkins自动化发布cicd

基础第一种方式:

pipeline {
  agent {
    kubernetes {
        inheritFrom "jenkins-slave"
        yaml '''
apiVersion: v1
kind: Pod
metadata:
  name: jenkins-slave
spec:
  containers:
  - name: jnlp
    image: "192.168.110.131/library/jenkins-slave-jdk:11"
    volumeMounts:
      - name: docker-cmd
        mountPath: /usr/bin/docker
      - name: docker-sock
        mountPath: /var/run/docker.sock
      - name: maven-cache
        mountPath: /root/.m2
  volumes:
    - name: docker-cmd
      hostPath:
        path: /usr/bin/docker
    - name: docker-sock
      hostPath:
        path: /var/run/docker.sock
    - name: maven-cache
      hostPath:
        path: /tmp/.m2
'''
    }
  }
    parameters {
      gitParameter branch: '', branchFilter: '.*', defaultValue: '', description: '请选择发布的代码分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'GitParameterDefinition'
      choice choices: ['1', '3', '5'], description: '请选择pod副本数', name: 'Replicas'
      choice choices: ['default', 'dev', 'test'], description: '请选择部署的命名空间', name: 'Namespace'
    }

    stages {
        stage('拉取代码'){
          steps {
            checkout scmGit(branches: [[name: '$Branch']], extensions: [], userRemoteConfigs: [[credentialsId: '7e837c29-b2ae-4a98-a36f-b81b43550f19', url: 'http://192.168.110.131:88/root/java-demo2.git']])
          }
        }
        stage('代码编译'){
          steps {
            sh """
            java -version
            JAVA_HOME=/usr/local/jdk1.8.0_45/ mvn clean package -Dmaven.test.skip=true
            """
          }
        }
        stage('构建推送镜像'){
          steps {
            sh """
                      unzip target/*.war -d target/ROOT  
                      echo '
                        FROM lizhenliang/tomcat
                        LABEL maitainer xinhuixu
                        ADD target/ROOT /usr/local/tomcat/webapps/ROOT
                      ' > Dockerfile
                      docker build -t registry.cn-hangzhou.aliyuncs.com/xinhuixu/private:javademov3 .
                      docker login -u 17563074175 -p 'xinhuixu1' registry.cn-hangzhou.aliyuncs.com
                      docker push registry.cn-hangzhou.aliyuncs.com/xinhuixu/private:javademov3
            """
          }
        }
        stage('K8S部署'){
          steps {
            configFileProvider([configFile(fileId: 'cabe64d8-16c1-4bde-bf6b-6970567067e2', targetLocation: 'admin.kubeconfig')]) {
            // some block
            }
            sh """
            sed -i 's#IMAGE#registry.cn-hangzhou.aliyuncs.com/xinhuixu/private:javademov3#' deploy.yaml
            sed -i "s#REOLICAS#$Replicas#" deploy.yaml
            kubectl apply -f deploy.yaml --kubeconfig=admin.kubeconfig -n $Namespace
            """
          }
        }
    }
}

第二种方式

def registry = "192.168.110.141"
pipeline {
  agent {
    kubernetes {
      inheritFrom "jenkins-slave"
      yaml """
apiVersion: v1
kind: Pod
metadata:
    name: jenkins-slave
spec:
  containers:
  - name: jnlp
    image: "${registry}/library/jenkins-slave-jdk:1.8"
    volumeMounts:
      - name: docker-cmd
        mountPath: /usr/bin/docker
      - name: docker-sock
        mountPath: /var/run/docker.sock
      - name: maven-cache
        mountPath: /root/.m2
  volumes:
    - name: docker-cmd
      hostPath:
        path: /usr/bin/docker
    - name: docker-sock
      hostPath:
        path: /var/run/docker.sock
    - name: maven-cache
      hostPath:
        path: /tmp/m2
"""
    }
  }
  //定义步骤变量
  environment { 
      harbor_project = "ms"
      gitlab_addr = "http://192.168.110.131:88/root/ms.git"
      gitlab_auth = "9ea7b777-ce8d-4448-828f-16afebc9f4b2"
      harbor_auth = "f227b16b-9cca-4d44-b04c-156eb8bb0463"
      k8s_auth = "4934a655-bb40-409b-89a7-ae4454463313"
  }
//  ## 设置日志时间输出(可用于阶段级别)
  options { timestamps() }
    parameters {
      gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '请选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'GitParameterDefinition'
      extendedChoice description: '请选择发布的微服务', multiSelectDelimiter: ',', name: 'Services', quoteValue: true, saveJSONParameterToFile: false, type: 'PT_CHECKBOX', value: 'portal-service:8080,gateway-service:9999,product-service:8010,stock-service:8030,order-service:8020', visibleItemCount: 5
      choice choices: ['mychart-port'], description: 'Chart部署模板', name: 'ChartName'
      choice choices: ['1', '2', '3'], description: '请选择pod副本数', name: 'Replicas'
      choice choices: ['default', 'dev', 'test'], description: '请选择命名空间', name: 'Namespace'
    }
    stages {
        stage('1、拉取代码'){
          steps {
            checkout scmGit(branches: [[name: "$Branch"]], extensions: [], userRemoteConfigs: [[credentialsId: "$gitlab_auth", url: "$gitlab_addr"]])
            }
          }
        stage('2、代码编译'){
            steps {
                sh "JAVA_HOME=/usr/local/jdk1.8.0_45 mvn clean package -Dmaven.test.skip=true"
                }
            }
        stage('3、构建镜像并推送镜像仓库'){
            steps {
                withCredentials([usernamePassword(credentialsId: "$harbor_auth", passwordVariable: 'password', usernameVariable: 'username')]) {
                sh """
                    docker login -u ${username} -p '${password}' ${registry}
                    for service in \$(echo $Services | sed 's/,/ /g'); do
                        service_name=\${service%:*}
                        image_name=${registry}/${harbor_project}/\${service_name}:${BUILD_NUMBER}
                        # 业务程序需进入biz目录里构建
                        cd \${service_name}
                        if ls |grep biz &>/dev/null; then
                          cd \${service_name}-biz
                        fi
                        docker build -t \${image_name} .
                        docker push \${image_name}
                        cd ${WORKSPACE}
                    done
                """
                }
            }
        }
        stage('4、k8s部署'){
            steps {
                configFileProvider([configFile(fileId: "$k8s_auth", targetLocation: 'admin.kubeconfig')]) {} //写到当前目录(程序源代码目录)
                sh """
                    for service in \$(echo $Services | sed 's/,/ /g'); do
                        //定义变量
                        service_name=\${service%:*}
                        service_port=\${service#*:}
                        image_name=${registry}/${harbor_project}/\${service_name}:${BUILD_NUMBER}
                        sed -i 's#IMAGE#image_name#' deploy.yaml
                        sed -i "s#REOLICAS#$Replicas#" deploy.yaml
                        sed -i "s##$service_port#" deploy.yaml
                        sed -i "
                        kubectl apply -f deploy.yaml --kubeconfig=admin.kubeconfig -n ${Namespace}
                    done
                """
            }
        }
    }
}

你可能感兴趣的:(jenkins,自动化,运维)