K8S RBAC基于服务账号授权案例
serviceaccount:
一般用于程序的用户名。
新建一个 serviceAccout 目录,在这里边操作
创建方式 -
响应式创建serviceAccounts
kubectl create serviceaccount baimei-linux86
kubectl get sa # 获取 serciAccounts 账号
kubectl delete sa baimei-linux86
声明式创建serviceaccount
cat 01-sa.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: baimei-linux86
namespace: default
kubectl apply -f 01-sa.yaml
kubectl get sa
接下来我们用一个应用程序来演示一下:
- 授权容器中的Python程序对K8S API访问权限案例
授权容器中Python程序对K8S API访问权限步骤:
- 创建Role;
- 创建ServiceAccount;
- 将ServiceAccount于Role绑定;
- 为Pod指定自定义的SA;
- 进入容器执行Python程序测试操作K8S API权限
基于服务账号授权案例
cat 01-sa-rabc.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: baimei-python
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: baimei-pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
#- apiGroups: ["apps"]
# resources: ["deployments"]
# verbs: ["get", "watch", "list"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: baimei-sa-to-role
subjects:
- kind: ServiceAccount
name: baimei-python
roleRef:
kind: Role
name: baimei-pod-reader
apiGroup: rbac.authorization.k8s.io
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: baimei-python3-sa
spec:
replicas: 2
selector:
matchExpressions:
- key: apps
values:
- "python"
operator: In
template:
metadata:
labels:
apps: python
spec:
# 指定sa的名称,请确认该账号是有权限访问K8S集群的哟!
serviceAccountName: baimei-python
containers:
- image: harbor.baimei.com/baimei-tools/python:3.9.16-alpine3.16
name: c1
command:
- tail
- -f
- /etc/hosts
kubectl apply -f 01-sa-rabc.yaml
验证一下:
-
编写Python程序,进入到"python"Pod所在的容器执行以下Python代码即可!
kubectl get pods
kubectl exec -it baimei-python3-sa-799bdd87b4-4cdsh -- sh
进入容器 下载 python依赖
pip install kubernetes -i https://pypi.tuna.tsinghua.edu.cn/simple/
创建文件;
cat > view-k8s.py <<'EOF'
from kubernetes import client, config
with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as f:
token = f.read()
configuration = client.Configuration()
configuration.host = "https://kubernetes" # APISERVER地址
configuration.ssl_ca_cert="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" # CA证书
configuration.verify_ssl = True # 启用证书验证
configuration.api_key = {"authorization": "Bearer " + token} # 指定Token字符串
client.Configuration.set_default(configuration)
apps_api = client.AppsV1Api()
core_api = client.CoreV1Api()
try:
print("###### Deployment列表 ######")
# 列出default命名空间所有deployment名称
for dp in apps_api.list_namespaced_deployment("default").items:
print(dp.metadata.name)
except:
print("没有权限访问Deployment资源!")
try:
# 列出default命名空间所有pod名称
print("###### Pod列表 ######")
for po in core_api.list_namespaced_pod("default").items:
print(po.metadata.name)
except:
print("没有权限访问Pod资源!")
EOF
测试:
python view-k8s.py