1. 手动创建原因
云环境自带的,一般会自动生成identity,或者用相关命令创建,比如Google的gke,需要创建GSA和KSA,然后用KSA impersonate(模仿)GSA,生成json形式的key文件,就可以用gcloud命令授权使用了,具体可点击此处查看gke的ksa授权详情。
kubeadmin安装的k8s,用户家目录中的 .kube/config 里面保存了客户端访问API Server的密钥相关信息,可以直接copy,二进制安装的不存在,需要手动生成包含user account的kubeconfig,k8s版本1.18,步骤如下:
1.1. 创建useraccount
此处创建的是全局性的用户账户,只是通过认证Authentication,还没有绑定集群角色。
User name为jenkins的用户向名称为kubernetes的k8s发起authentication,关于ca签名认证的原理,这里不在赘述,可参看其他文章。
执行如下脚本生成名称为jenkins.kubeconfig的kubeconfig文件:
cat kubeconfig.sh
KUBE_APISERVER="https://10.70.128.50:6443"
# 设置集群参数
kubectl config set-cluster kubernetes \
--certificate-authority=/opt/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=jenkins.kubeconfig
# 设置客户端认证参数
kubectl config set-credentials jenkins \
--client-certificate=/opt/kubernetes/ssl/server.pem \
--client-key=/opt/kubernetes/ssl/server-key.pem \
--embed-certs=true \
--kubeconfig=jenkins.kubeconfig
# 设置上下文参数
kubectl config set-context default \
--cluster=kubernetes \
--user=jenkins \
--kubeconfig=jenkins.kubeconfig
# 设置默认上下文
kubectl config use-context default --kubeconfig=jenkins.kubeconfig
执行sh kubeconfig.sh 生成名称为jenkins.kubeconfig的kubeconfig文件
1.2. 基于RBAC(基于角色访问控制)的授权Authorization,创建以下集群角色,并绑定上面创建的user:jenkins
cat jenkins_rbac.yml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: myclusterrole
rules:
- apiGroups: [""]
resources: ["pods","services"]
verbs: ["get", "watch", "list", "delete", "create", "update"]
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["extensions", "apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: clusterrolebinding-myclusterrole
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: myclusterrole
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: jenkins
创建并绑定角色:kubectl apply -f jenkins_rbac.yml
注意,下面截图的User,应为jenkins
2. Jenkins安装Config File Provider插件,将生产的kubeconfig文件粘贴到如下图中Jenkins的位置:
cat jenkins.kubeconfig
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: LS0tLS...
server: https://10.70.128.50:6443
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: jenkins
name: default
current-context: default
kind: Config
preferences: {}
users:
- name: jenkins
user:
client-certificate-data: LS0tLS...
client-key-data: LS0tLS1CRUdJT...
3. pipeline使用
设置完成,就可以通过在pipeline中configFileProvider([configFile(fileId: "${k8s_auth}", targetLocation: "admin.kubeconfig")])
来使用