目標
- 創建新命名空間 tommy
- 創建只能管理 tommy 命名空間下資源的 kubeconfig
步驟
創建密鑰
openssl genrsa -out tommy.key 2048
為密鑰創建證書簽名申請(CSR)
openssl req -new -key tommy.key -out tommy.csr -subj "/CN=tommy/O=student"
# 用戶名:tommy
# 組:student
將證書簽名申請提交到 k8s
kubectl apply -f - <<EOF
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: tommy
spec:
groups:
- system:authenticated
request: $(openssl base64 -e -A < tommy.csr)
signerName: kubernetes.io/kube-apiserver-client
usages:
- client auth
EOF
k8s 批准簽名申請,生成(已簽名)證書
kubectl certificate approve tommy
導出證書
kubectl get certificatesigningrequests/tommy -o jsonpath='{.status.certificate}' | openssl base64 -d -A >tommy.crt
刪除證書簽名申請
rm tommy.csr
kubectl delete certificatesigningrequests/tommy
生成新的 kubeconfig
kubectl config view --raw -o json | python3 -c '
import base64
import json
import sys
user_name = "tommy"
with open(user_name + ".key") as f:
ckd = base64.b64encode(f.read().encode()).decode()
with open(user_name + ".crt") as f:
ccd = base64.b64encode(f.read().encode()).decode()
config = json.loads(sys.stdin.read())
for context in config["contexts"]:
if context["name"] == config["current-context"]:
context = context["context"]
break
else:
assert False
for cluster in config["clusters"]:
if cluster["name"] == context["cluster"]:
cluster = cluster["cluster"]
break
else:
assert False
sys.stdout.write(
"""\
apiVersion: v1
kind: Config
current-context: default
contexts:
- name: default
context:
cluster: default
user: {user_name}
namespace: {user_name}
clusters:
- name: default
cluster:
server: {s}
certificate-authority-data: {cad}
users:
- name: {user_name}
user:
client-key-data: {ckd}
client-certificate-data: {ccd}
""".format(
user_name=user_name,
s=cluster["server"],
cad=cluster["certificate-authority-data"],
ckd=ckd,
ccd=ccd,
)
)
' > tommy.kubeconfig
創建 tommy 命名空間
kubectl create namespace tommy
在命名空間創建 admin 角色
kubectl apply -f - <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: tommy
name: admin
rules:
- apiGroups:
- '*'
resources:
- '*'
verbs:
- '*'
EOF
a)創建角色綁定,將(tommy 命名空間的)admin 角色綁定到用戶 tommy 上
kubectl apply -f - <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
namespace: tommy
name: tommy
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: admin
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: tommy
EOF
b)創建角色綁定,將(tommy 命名空間的)admin 角色綁定到組 student 上
kubectl apply -f - <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
namespace: tommy
name: tommy
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: admin
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: Group
name: student
EOF
a、b二選一
測試
KUBECONFIG=./tommy.kubeconfig kubectl get pods
# 輸出
# No resources found in tommy namespace.
沒有報錯表示成功