k8s

DevOps之Jenkins集成Kubernetes

2022-07-12  本文已影响0人  羋学僧

1、 Jenkins集成Kubernetes

1.1、 准备部署的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.117.112:80/repo/pipeline:v3.0.0
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  namespace: test
  name: pipeline
  labels:
    app: pipeline
spec:
  selector:
    app: pipeline
  ports:
  - port: 8081
    targetPort: 8080
  type: NodePort
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: test
  name: pipeline
spec:
  ingressClassName: ingress
  rules:
  - host: mhg.pipeline.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: pipeline
            port:
              number: 8081
1.2、 Harbor私服配置

在尝试用kubernetes的yml文件启动pipeline服务时,会出现Kubernetes无法拉取镜像的问题,这里需要在kubernetes所在的Linux中配置Harbor服务信息,并且保证Kubernetes可以拉取Harbor上的镜像

1.3、 测试使用效果

执行kubectl命令,基于yml启动服务,并且基于部署后服务的提示信息以及Ingress的设置,直接访问

1.4、 Jenkins远程调用
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)])
              }
          }

传递yml文件脚本
stage('远程执行k8s-master的kubectl命令') {
              steps {
                  sh 'ssh root@192.168.117.113 kubectl apply -f /usr/local/k8s/pipeline.yml'
              }
          }
设置Jenkinsfile

Ps:这种方式更适应与CD操作,将项目将基于某个版本部署到指定的目标服务器

2、 基于GitLab的WebHooks

这里要实现自动化的一个CI操作,也就是开发人员Push代码到Git仓库后,Jenkins会自动的构建项目,将最新的提交点代码构建并进行打包部署,这里区别去上述的CD操作,CD操作需要基于某个版本进行部署,而这里每次都是将最新的提交点集成到主干上并测试。

2.1、 WebHooks通知

开启Jenkins的自动构建

构建触发器

设置Gitlab的Webhooks

设置Gitlab的Webhooks

需要关闭Jenkins的Gitlab认证

关闭Jenkins的Gitlab认证

再次测试Gitlab

再次测试
2.2、 修改配置

修改Jenkinsfile实现基于最新提交点实现持续集成效果,将之前引用${tag}的全部去掉

// 所有的脚本命令都放在pipeline中
pipeline {
    agent any
    environment{
        harborHost = '192.168.117.112:80'
        harborRepo = 'repo'
        harborUser = 'admin'
        harborPasswd = 'Harbor12345'
    }
    stages {

        stage('拉取Git代码') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: 'http://192.168.117.111:8929/root/devopsdemo.git']]])
            }
        }

        stage('构建代码') {
            steps {
                sh '/var/jenkins_home/maven/bin/mvn clean package -DskipTests'
            }
        }

        stage('检测代码质量') {
            steps {
                sh '/var/jenkins_home/sonar-scanner/bin/sonar-scanner -Dsonar.sources=./ -Dsonar.projectname=${JOB_NAME} -Dsonar.projectKey=${JOB_NAME} -Dsonar.java.binaries=target/ -Dsonar.login=dc4cbe2bca153ad1baf5adba7e02ddd2288ef53f' 
            }
        }
        

        stage('制作自定义镜像并发布Harbor') {
            steps {
                sh '''cp ./target/*.jar ./docker/
                cd ./docker
                docker build -t ${JOB_NAME}:latest ./'''
  
                sh '''docker login -u ${harborUser} -p ${harborPasswd} ${harborHost}
                docker tag ${JOB_NAME}:latest ${harborHost}/${harborRepo}/${JOB_NAME}:latest
                docker push ${harborHost}/${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.117.113 kubectl apply -f /usr/local/k8s/pipeline.yml'
              }
          }
    }
    post {
        success {
            dingtalk (
                robot: 'Jenkins-DingDing',
                type:'MARKDOWN',
                title: "success: ${JOB_NAME}",
                text: ["- 成功构建:${JOB_NAME}项目!\n- 版本:latest\n- 持续时间:${currentBuild.durationString}\n- 任务:#${JOB_NAME}"]
              )
          }
        failure {
            dingtalk (
                robot: 'Jenkins-DingDing',
                type:'MARKDOWN',
                title: "fail: ${JOB_NAME}",
                text: ["- 失败构建:${JOB_NAME}项目!\n- 版本:latest\n- 持续时间:${currentBuild.durationString}\n- 任务:#${JOB_NAME}"]
              )
        }
    }
}

修改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.117.112:80/repo/pipeline:latest   # 这里
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
# 省略其他内容…………
2.3、 滚动更新

因为pipeline没有改变时,每次不会重新加载,这样会导致Pod中的容器不会动态更新,这里需要使用kubectl的rollout restart命令滚动更新

stage('远程执行k8s-master的kubectl命令') {
              steps {
                  sh '''ssh root@192.168.117.113 kubectl apply -f /usr/local/k8s/pipeline.yml
                ssh root@192.168.117.113 kubectl rollout restart deployment pipeline -n test'''
              }
          }
设置Jenkinsfle

目前DevOps架构图

上一篇 下一篇

猜你喜欢

热点阅读