先在k8s集群上测试获取借口的Token:

curl --header "Authorization: Bearer $TOKEN" --insecure -XGET https://192.168.0.45:6443/api/v1/nodes

查看已有的或创建Token:

kubectl create serviceaccount dashboard-admin -n kube-system
kubectl create clusterrolebinding admin-k8s-dashboard --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin
kubectl get secret -n kube-system
kubectl describe secret dashboard-admin-token-cxls2 -n kube-system

测试token:将上面的$TOKEN换成token的值来测试token是否可用。

curl --header "Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IlUzcFlsZmdEQWpRRm13RnRsa1BTTXdfcUwwVzFobUFNSUlUUENtUGhQbDAifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tYmJmYmQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiZDJiZmY3YzAtYzdmOS00NmM4LWFhZDktODA1YzcxNWExYjM5Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.e1bROxgrN-MO1kXjL7yCVamGEZZGjknMOEaWU0F5LmdqWzPembLsq0M6UStw_HoOyTxLszD_NacLyzDEjVwLZ9c8oJeiwyTKhaSuRuBfCEXQ9tdNaMdFfo00ThO9hVAOsVIxY2M1e4XV8F2eT-j6VBnsaUqaGDaodkwccDLt_qphVUyGBj35N2OddrtEn3cQG9oSMuN6n7_C8mqJ_lTnCehCdIA36Vih4pqYs_uCoQ0Ltesc9ueQ7ahOjHKgPrf63zm-xc931mVpvVPa8r7ADXCjiL99ryrCn8r2RMKQEOATmUB2fO826Ua2NaneV4D5BaCN_JQebZjTLf5gzJOSAA" --insecure -XGET https://192.168.0.45:6443/api/v1/nodes

将token添加到全局凭据里面:

        Jenkins > 凭据 > 系统 > 全局凭据 (unrestricted) > 添加凭据 > 类型(Secret text)。

安装jenkins插件:

在jenkins插件列表中搜索“HTTP Request”的插件,并安装。

插件官方文档:

https://www.jenkins.io/doc/pipeline/steps/http_request/

在pipeline中封装http_request 请求:  src/org/devops/kubernetes.groovy  

package org.devops


//封装HTTP请求
def HttpReq(reqType,reqUrl,reqBody){
    def apiServer = "https://192.168.0.45: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 CreateDeployment(nameSpace,deployName,deplyBody){
    apiUrl = "namespaces/${nameSpace}/deployments/"
    response = HttpReq('POST',apiUrl,deplyBody)
    println(response)
}

//删除deployment
def DeleteDeployment(nameSpace,deployName){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('DELETE',apiUrl,deplyBody)
    println(response)
}

//更新Deployment
def UpdateDeployment(nameSpace,deployName,deplyBody){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('PUT',apiUrl,deplyBody)
    println(response)
}

//获取Deployment
def GetDeployment(nameSpace,deployName){
    apiUrl = "namespaces/${nameSpace}/deployments/${deployName}"
    response = HttpReq('GET',apiUrl,'')
    return response
}

在pipeline中使用借口获取资源:

stage("deployment"){
	steps{
		script{
			tools.PrintMes("GetDeployment","green")
			response = k8s.GetDeployment("kube-system", "coredns")
			response = response.content
			println(response) // print deployment content
			
			fileData = readYaml text: """${response}"""
			println(fileData)
			println(fileData["spec"]["template"]["spec"]["containers"][0]["image"])
			
			// 修改镜像
			fileData["spec"]["template"]["spec"]["containers"][0]["image"] = "myharbor.com/solo/solo:0.4"
			println(fileData["spec"]["template"]["spec"]["containers"][0]["image"])
			tools.PrintMes("newimage", "green")
			println(fileData)
		}
	}
}