外部Jenkins集成k8s

IT
IT
IT
405
文章
1
评论
2021年4月1日18:37:58 评论 5,551 4729字阅读15分45秒

创建Jenkins凭据

  • 获取k8s具有管理员的token
[root@k8s ~]# kubectl -n kubernetes-dashboard describe secret $(kubectl -n kubernetes-dashboard get secret | grep admin-user | awk '{print $1}')
Name: admin-user-token-nc4bz
Namespace: kubernetes-dashboard
Labels: <none>
Annotations: kubernetes.io/service-account.name: admin-user
kubernetes.io/service-account.uid: 2554098c-26ed-4a89-8652-d80f28187b4a

Type: kubernetes.io/service-account-token

Data
====
ca.crt: 1025 bytes
namespace: 20 bytes
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IlZLZDBmbkd6amM2SmVlTjA2a3B2RUtrNTBOWTZlQVFPYW84MF9Za291R3MifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLW5jNGJ6Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIyNTU0MDk4Yy0yNmVkLTRhODktODY1Mi1kODBmMjgxODdiNGEiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZXJuZXRlcy1kYXNoYm9hcmQ6YWRtaW4tdXNlciJ9.bUd0q-dqn6YtA17Un7_nLqUNjM3qpLxA3Yw7VuCVEI8KroX9csplGtzsnjHwoFnB5WxYCUW_X6Vjjv06iYvZwAPDsP0mkZNd99-JY4_KO5ms87ByExMZZ2jsEdTZfmEy4w73uW48Pf_0N6km18deGpEonzz3OBP4AvnMdOoKWuFU3clo8dqtDD46w5NG2SFE-r48XYoWmM-kt6kxl-JQtQZTUYXKjxzJqHZF4vexR8TIjYxRu4Ai0Sw_HTcK0N5oL33keorRJ2VglZ8RDqDdpTIwId0i6RBc0rsOWs_337VNyjbMadvmFfixtU8J0vtSWBQRbw13w7kFUNvwcw1wbg
  • 复制token添加到Secret

外部Jenkins集成k8s

封装api

  • kubernetes.groovy
package org.devops

//封装HTTP请求
def HttpReq(reqType,reqUrl,reqBody){
    def apiServer = "https://192.168.90.22:6443/apis/apps/v1"
    withCredentials([string(credentialsId: 'kubernetes-token', variable: 'kubernetestoken')]) {
      result = httpRequest customHeaders: [[maskValue: true, name: 'Authorization', value: "Bearer ${kubernetestoken}"],
                                           [maskValue: false, name: 'Content-Type', value: 'application/yaml'], 
                                           [maskValue: false, name: 'Accept', value: 'application/yaml']], 
                httpMode: reqType, 
                consoleLogResponseBody: true,
                ignoreSslErrors: true, 
                requestBody: reqBody,
                url: "${apiServer}/${reqUrl}"
                //quiet: true
    }
    return result
}
//获取Deployment
def GetDeployment(nameSpace,deployName){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('GET',apiUrl,'')
    def datas = readYaml text: """${response.content}"""
    println(datas)
}
  • 引入k8s
#!groovy

@Library('jenkinslibrary@master') _

//func from shareibrary
def build = new org.devops.build()
def tools = new org.devops.tools()
def toemail = new org.devops.toemail()
def sonar = new org.devops.sonarqube()
def nexus = new org.devops.nexus()
def k8s = new org.devops.kubernetes()

def runOpts
//env
String buildType = "${env.buildType}"
String buildShell = "${env.buildShell}"
String srcUrl = "${env.srcUrl}"
String branchName = "${env.branchName}"


if ("${runOpts}" == "GitlabPush"){
    branchName = branch - "refs/heads/"
    
    currentBuild.description = "Trigger by ${userName} ${branch}"
    gitlab.ChangeCommitStatus(projectId,commitSha,"running")
    env.runOpts = "GitlabPush"

    
} else {
   userEmail = "lucky@centoscn.vip"
}


//pipeline
pipeline{
    agent { node { label "master"}}
    
    
    stages{

        stage("检出代码"){
            steps{
                script{
                   
                    
                    println("${branchName}")
                
                    tools.PrintMes("获取代码","green")
                    checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                                      doGenerateSubmoduleConfigurations: false, 
                                      extensions: [], 
                                      submoduleCfg: [], 
                                      userRemoteConfigs: [[credentialsId: 'c0aa7de6-9f94-4445-894b-f12f81eca5a8', url: "${srcUrl}"]]])

                }
            }
        }
        stage("编译打包"){
            steps{
                script{
                
                    tools.PrintMes("执行打包","green")
                    build.Build(buildType,buildShell)
                    nexus.main("nexus")
                }
            }
       }
        stage("代码扫描"){
            steps {
                 script{
                     tools.PrintMes("代码扫描","green")
                     sonar.SonarScan("${JOB_NAME}","${JOB_NAME}","src")
                }
            } 
        }
          
        stage("构建镜像"){
            steps {
                 script{
                     tools.PrintMes("构建上传镜像","green")
                     env.serviceName = "${JOB_NAME}".split("_")[0]
                       
                      withCredentials([usernamePassword(credentialsId: 'aliyun-registry-admin', passwordVariable: 'password', usernameVariable: 'username')]) {
                           
                          env.dockerImage = "registry.cn-beijing.aliyuncs.com/devops-vp/prod/${serviceName}:${branchName}"
                           sh """
                                docker login -u ${username} -p ${password}  registry.cn-beijing.aliyuncs.com
                                docker build -t registry.cn-beijing.aliyuncs.com/devops-vp/prod/${serviceName}:${branchName} .
                                sleep 1
                                docker push registry.cn-beijing.aliyuncs.com/devops-vp/prod/${serviceName}:${branchName}
                                sleep 1
                                #docker rmi registry.cn-beijing.aliyuncs.com/devops-vp/prod/${serviceName}:${branchName}
                            """
                        }
                    }
                }
            } 
        stage("发版到k8s"){
            steps {
                 script{
                     tools.PrintMes("发布应用","green")
                     k8s.GetDeployment("devops","jenkins")
                     
                }
            } 
        }             
    }
    post {
        always{
            script{
                println("always")
            }
        }
        
        success{
            script{
                println("success")
                if ("${runOpts}" == "GitlabPush"){
                    gitlab.ChangeCommitStatus(projectId,commitSha,"success")
                }
                toemail.Email("流水线成功",userEmail)
            
            }
        
        }
        failure{
            script{
                println("failure")
                if ("${runOpts}" == "GitlabPush"){
                    gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
                }
                toemail.Email("流水线失败了!",userEmail)
            }
        }
        
        aborted{
            script{
                println("aborted")
                if ("${runOpts}" == "GitlabPush"){
                    gitlab.ChangeCommitStatus(projectId,commitSha,"canceled")
                }
               toemail.Email("流水线被取消了!",userEmail)
            }
        
        }
    
    }
    
    
}

 

测试

外部Jenkins集成k8s

报错

  • 提示这个

外部Jenkins集成k8s

  • 安装http插件即可

外部Jenkins集成k8s

继续阅读
  • 我的QQ
  • QQ扫一扫
  • weinxin
  • 我的头条
  • 头条扫一扫
  • weinxin
IT
  • 本文由 发表于 2021年4月1日18:37:58
  • 除非特殊声明,本站文章均为原创,转载请务必保留本文链接
jenkinsfile集成阿里云镜像仓库 jenkins-ci/cd

jenkinsfile集成阿里云镜像仓库

创建Jenkins认证授权 ID也配置成aliyun-registry-admin 阿里云镜像库有个问题,在设置固定密码后,使用的是本账号名字。本账号的密码和镜像的密码也就不一样了。所以要么单独创建一...

您必须才能发表评论!