前言
- k8s中有默认的几个角色
- role:特定命名空间访问权限
- ClusterRole:所有命名空间的访问权限
- 角色绑定
- roleBinding:角色绑定到主体
- ClusterRoleBinding:集群角色绑定到主体
- 主体
- user:用户
- group:用户组
- serviceAccount:服务账号
- 角色绑定主题有两种方式:
- 绑定kind为service account
- 绑定kind为user
一、 在集群内拿到Token
1.1 创建命名空间sademo
# 创建命名空间
kubectl create ns sademo
1.2 创建角色sa-role
sa-role.yaml ```yaml kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: namespace: sademo # namespace的name,可更改 name: sa-role # role的name,可更改 rules:# 创建角色
# 新建role yaml文件
vim sa-role.yaml
# 执行
kubectl apply -f sa-role.yaml
- apiGroups: [“”] # “” indicates the core API group resources: [“pods”] verbs: [“get”, “watch”, “list”]
<a name="wTBlP"></a>
### 1.3 创建角色绑定user-rolebinding
```shell
#创建serviceAccount
kubectl create serviceaccount sa-sa
# 创建roleBinding yaml文件
vim user-rolebinding.yaml
kubectl apply -f user-rolebinding.yaml
1.5 service account绑定(kind 是service account)
service account绑定的yaml
sa-roleRinding.yaml
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: sa-rolebinding
namespace: sademo
subjects:
- kind: ServiceAccount
name: sa-sa # Name is case sensitive
namespace: sademo
roleRef:
kind: Role #this must be Role or ClusterRole
name: sa-role # this must match the name of the Role or ClusterRole you wish to bind to
apiGroup: rbac.authorization.k8s.io
1.5.1 在pod中使用service account
# 创建pod
vim sa-nginx-pod.yaml
执行
kubectl apply -f sa-nginx-pod.yaml
# 查看pod的信息
kubectl describe pod sa-nginx-pod
# 进入pod内部
# ab-nginx-pod 为新创建的pod的名称 可以通过 kubect get pod 查看
kubectl exec -it sa-nginx-pod -- /bin/bash
# 生成CA和Tocken
root@sa-nginx-pod:/#
export CURL_CA_BUNDLE=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
root@sa-nginx-pod:/#
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
# 使用curl 获取 pods列表
root@sa-nginx-pod:/#
curl -H "Authorization: Bearer $TOKEN" https://10.4.104.169:6443/api/v1/namespaces/defult/pods
kubectl exec it sa-nginx-pod -- /bin/sh
cd /var/run/secrets/kubernetes.io/serviceaccount
cat token
sa-nginx-pod.yaml:
apiVersion: v1
kind: Pod
metadata:
name: sa-nginx-pod
spec:
serviceAccountName: sa-sa
containers:
- image: nginx:latest
name: nginx
二、验证能否在集群外拿到Tocken
# 获取service account
kubectl get serviceaccount
# 查看service account 信息
kubectl describe sa sa-sa
# 查看secret 的json信息
kubectl get secret secret的name -o json
# 转换Token
echo "Tocken" | base64 --decode
三、 验证Tocken是否相同
根据截图,相同√
"eyJhbGciOiJSUzI1NiIsImtpZCI6IlhGbHRva3gyMDB6RnJoYlBhRjJ0XzdvdVZZZjNBLU5ONHhEMFVGdmNiN0EifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6InNhLXNhLXRva2VuLXZ0YjJ0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6InNhLXNhIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiODljOGVlYWEtZGY5Mi00NjI2LWJkMzUtOTczZmRlODlhYWUyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6c2Etc2EifQ.DdhVDUO6azpa9bY-803SvFm-YAyz4pSOspFBLts91mnxaQEH9AY-yTJt1DR8QBMVz4XnIY0bckkq3SJoIq_ZgOdcBl31EM7srvPl67hkjYF1562i3YmOfDj3D7b3X7hrB3xKdpbK9youlqAtalfR9DnvP3c9H4n5asI2Nu37IoxBuEPLv7Ke_mizfb638sV4rNyhKzx7WWeyLIxmebk-_C7_F6rZlGLgG3245OwLwvYu_HSiZtcRMeK9-pM417PXLqAVOJ5g1VKgn30jXXs6U0ht0DMylziv2en1q_iQfT3YAPfVenqjtaBxmlnZlGuiA9rXGFuCuBxiCWe7viP6Qw"
四、用代码测试
package main
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
func getConfig() *rest.Config {
config := rest.Config{
// Host: "https://10.2.238.171:6443",
Host: "https://10.4.104.169:6443",
// ContentConfig: rest.ContentConfig{
// GroupVersion: &v1.SchemeGroupVersion,
// NegotiatedSerializer: scheme.Codecs.WithoutConversion(),
// },
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
// BearerToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6IlhlazJtR3QxTGQ0OEhrN1ZoZWE2d2NuenZEbEc4WjNSeXV6RnlvUEpobEUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImN2YmFja3VwLXRva2VuLTg5OHQ3Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImN2YmFja3VwIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiZDRjYTE0NzQtNTM5Yy00Y2FhLTllNDMtNmM3OWUwNDQwYTExIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6Y3ZiYWNrdXAifQ.GY4UVEt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Ke_mizfb638sV4rNyhKzx7WWeyLIxmebk-_C7_F6rZlGLgG3245OwLwvYu_HSiZtcRMeK9-pM417PXLqAVOJ5g1VKgn30jXXs6U0ht0DMylziv2en1q_iQfT3YAPfVenqjtaBxmlnZlGuiA9rXGFuCuBxiCWe7viP6Qw",
}
return &config
}
func main() {
// 设置资源组合版本
gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
// 获取config对象
config := getConfig()
// 获取动态客户端
dynamicClient, _ := dynamic.NewForConfig(config)
//获取deployment资源
resStruct, _ := dynamicClient.Resource(gvr).Namespace("default").Get(context.TODO(), "mysql", metav1.GetOptions{})
// 将unstructured序列化成json
j, _ := resStruct.MarshalJSON()
// 打印json
fmt.Println(string(j))
}
结果:
附录(以下是错误尝试记录)
一、 尝试不在Linux下创建用户
用户名user绑定(kind是User)
角色绑定的yaml
user-rolebinding.yaml
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: user-rolebingding # roleBinding的name,可更改
namespace: sademo
subjects:
- kind: User
name: lucy # Name is case sensitive
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role #this must be Role or ClusterRole
name: sa-role # this must match the name of the Role or ClusterRole you wish to bind to
apiGroup: rbac.authorization.k8s.io
1.4.1 创建角色的文件夹
mkdir /usr/local/k8s/lucy
vim lucy-csr.json
lucy-csr.json
{
"CN": "lucy",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing",
# Group
"O": "k8s",
"OU": "System"
}
]
}
1.4.2 下载证书工具:
mkdir /udr/local/bin
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod a+x *
到lucy的目录下查看kubenetes
ls /usr/local/k8s/lucy/etc/kubernetes/pki
1.4.3 生成令牌,设置各种参数
# 生成令牌
cfssl gencert -ca=ca.crt -ca-key=ca.key -profile=kubernetes /usr/local/k8s/lucy/lucy-csr.json | cfssljson -bare lucy
# ls 就能看到生成了lucy-key.pem,lucy.pem
# 进入Lucy 目录 设置集群参数
cd /usr/local/k8s/lucy
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--embed-certs=true \
--server=https://10.4.104.169:6443 \
--kubeconfig=lucy.kubeconfig
# 设置客户端认证参数
kubectl config set-credentials lucy \
--client-key=/etc/kubernetes/pki/lucy-key.pem \
--client-certificate=/etc/kubernetes/pki/lucy.pem \
--embed-certs=true \
--kubeconfig=lucy.kubeconfig
# 设置上下文参数
kubectl config set-context default \
--cluster=kubernetes \
--user=lucy \
--namespace=sademo \
--kubeconfig=lucy.kubeconfig
# 设置默认上下文(可以没有)
kubectl config use-context default --kubeconfig=lucy.kubeconfig
# 绑定角色空间
kubectl create rolebinding devuser-admin-binding \
--clusterrole=admin \
--user=lucy \
--namespace=sademo
# 进入Lucy,设置一个./kube文件
mkdir ./kube
# 将其复制到lucy目录下
cp lucy.kubeconfig /home/lucy/.kube
# 设置文件的所有者为lucy
chown lucy:lucy /home/lucy/.kube/lucy.kubeconfig
二、 CV官方提供测试Token
和以上操作一样,比以上更简洁,做测试使用
(以下是CV官方提供的测试命令)
# 要创建Kubernetes服务帐户(例如cvbackup)
kubectl create serviceaccount cvbackup
# 为确保服务帐户具有执行数据保护操作的足够特权,请将服务帐户添加到default-sa-crb群集角色绑定中
kubectl create clusterrolebinding default-sa-crb \
--clusterrole=cluster-admin \
--serviceaccount=default:cvbackup
# 提取配置Kubernetes集群以进行数据保护所需的服务帐户令牌。
kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='cvbackup')].data.token}"|base64 --decode