「Jenkins」- 连接 Kubernetes 集群

普通作业(Freestyle)

https://plugins.jenkins.io/kubernetes-cli
https://github.com/jenkinsci/kubernetes-cli-plugin

通过 Kubernetes CLI 插件,能够实现在 Job 中与 Kubernetes Cluster 交互,但是需要单独安装 kubectl 命令;

该插件的作用是管理 kubectl 命令的凭证,操作 k8s 集群时依旧需要使用 kubectl 命令;

支持的凭证类型有:
Token, as secrets (see Plain Credentials plugin)
Plain KubeConfig files (see Plain Credentials plugin)
Username and Password (see Credentials plugin)
Certificates (see Credentials plugin)
OpenShift OAuth tokens, as secrets (see Kubernetes Credentials plugin)

在 Jenkin 中添加凭证时,可以选择「secret file」类型,然后上传$HOME/.kube/config文件;

Within the Jenkins dashboard, select a Job and then select “Configure”
Scroll down to the “Build Environment” section
Select “Configure Kubernetes CLI (kubectl) with multiple credentials”
In the “Credential” dropdown, select the credentials to authenticate on the cluster or the kubeconfig stored in Jenkins.
Repeat 4 as necessary

流水线(Pipeline)

Kubernetes | Jenkins plugin

针对现有(11/23/2022)版本,在 Job 中,连接 Kubernetes 集群,依旧要使用 kubectl 命令;

withKubeConfig

传参较多,所以我们未使用该 Step 来加载配置;

withKubeCredentials

传参较多,所以我们未使用该 Step 来加载配置;

withCredentials

1)在 Jenkins Agent 中,部署 kubectl 命令(或通过 Custom Tools 部署);
2)在 Jenkins / Credential 中,创建连接集群的凭证信息;
3)在 Jenkins Pipeline 中,通过 withCredentials() 以文件的方式注入凭证,并通过 kubectl 使用;

withCredentials([file(credentialsId: 'kubeconfig_rivtower-developing-120', variable: 'KUBECONFIG')]) {
    // some block
    sh "kubectl version"
}