jenkins使用kubernetes插件连接k8s的认证方式
一、使用 rbac授权,token的方式连接k8s
1、rbac授权
#创建devops命名空间 kubectl create ns devops #创建serviceaccounts kubectl create sa devops-jenkins -n devops #对jenkins做cluster-admin绑定 kubectl create clusterrolebinding devops-jenkins-role-binding --clusterrole cluster-admin --serviceaccount=devops:devops-jenkins
2、获取token
kubernetes插件与k8s连接时,并不是直接使用serviceaccount,而是通过token。因此我们需要获取serviceaccount:jenkins对应的token。
# 1.查看sa [root@k8s-master ~]# kubectl get sa -n devops NAME SECRETS AGE default 1 13m devops-jenkins 1 12m # 2.查看secret [root@k8s-master ~]# kubectl describe sa devops-jenkins -n devops Name: devops-jenkins Namespace: devops Labels: <none> Annotations: <none> Image pull secrets: <none> Mountable secrets: devops-jenkins-token-x96qz Tokens: devops-jenkins-token-x96qz Events: <none> 3.获取token [root@k8s-master ~]# kubectl describe secrets devops-jenkins-token-x96qz -n devops Name: devops-jenkins Namespace: devops Labels: <none> Annotations: <none> Image pull secrets: <none> Mountable secrets: devops-jenkins-token-x96qz Tokens: devops-jenkins-token-x96qz Events: <none> You have new mail in /var/spool/mail/root [root@k8s-master ~]# kubectl describe secrets devops-jenkins-token-x96qz -n devops Name: devops-jenkins-token-x96qz Namespace: devops Labels: <none> Annotations: kubernetes.io/service-account.name: devops-jenkins kubernetes.io/service-account.uid: 79c03e73-8f2e-490b-a675-8b4b95e0bf08 Type: kubernetes.io/service-account-token Data ==== namespace: 6 bytes token: eyJhb...###这里就是所需的token
3.添加认证

4、kubernetes插件与k8s连接配置

禁用HTTPS证书检查
kubernetes地址:为k8s api server地址,通过调用apiserver操作k8s。可通过以下来查看:
[root@k8s-master ~]# kubectl cluster-info Kubernetes control plane is running at https://10.0.1.143:6443 CoreDNS is running at https://10.0.1.143:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'. You have new mail in /var/spool/mail/root
点击连接测试,看到k8s已经连接成功
二、使用证书的方式连接k8s
1、通过解码获取kubectl使用的admin证书
查看 /root/.kube/config文件,文件中有三个值 certificate-authority-data 、client-certificate-data 、 client-key-data
解码它们获得证书 ,注意将上面的值替换称自己的一大长传字符串
echo certificate-authority-data | base64 -d > ca.crt echo client-certificate-data | base64 -d > client.crt echo client-key-data | base64 -d > client.key
根据这三个文件生成一个PKCS12格式的客户端证书文件
openssl pkcs12 -export -out cert.pfx -inkey client.key -in client.crt -certfile ca.crt
注意生成证书的时候,一定要填写密码,添加凭证会用到
2、添加认证

3、kubernetes插件与k8s连接配置

将ca.crt中的内容填写 Kubernetes 服务证书 key
完成后点击测试连接已成功

浙公网安备 33010602011771号