Skip to content

Instantly share code, notes, and snippets.

@ydp
Created April 23, 2018 09:18
Show Gist options
  • Save ydp/a68cc4c5d3aa6d73a8e97d293f2da4a2 to your computer and use it in GitHub Desktop.
Save ydp/a68cc4c5d3aa6d73a8e97d293f2da4a2 to your computer and use it in GitHub Desktop.
创建k8s的namespace和sa,并分配给单独的pod权限
#!/bin/bash
ns=$1
sa=$ns
API_SERVER="https://10.87.52.188:6443"
kubectl create ns $ns
kubectl -n $ns create sa $sa
SECRET=$(kubectl -n $ns get sa $sa -o go-template='{{range .secrets}}{{.name}}{{end}}')
CA_CERT=$(kubectl -n $ns get secret ${SECRET} -o yaml | awk '/ca.crt:/{print $2}')
cat <<EOF > ${ns}.conf
apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority-data: $CA_CERT
server: $API_SERVER
name: cluster
EOF
TOKEN=$(kubectl -n $ns get secret ${SECRET} -o go-template='{{.data.token}}')
kubectl config set-credentials ${ns}-user --token=`echo ${TOKEN} | base64 -d` --kubeconfig=${ns}.conf
kubectl config set-context default --cluster=cluster --user=${ns}-user --kubeconfig=${ns}.conf
kubectl config use-context default --kubeconfig=${ns}.conf
cat <<EOF > ${ns}-user-role.yml
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: ${ns}
name: ${ns}-user-pod
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
EOF
kubectl create -f ${ns}-user-role.yml
kubectl create rolebinding ${ns}-view-pod --role=${ns}-user-pod --serviceaccount=${ns}:${ns} --namespace=${ns}
@ydp
Copy link
Author

ydp commented Apr 23, 2018

参考了
https://kairen.github.io/2018/01/08/kubernetes/rbac-sa-kubectl/

测试:

$ kubectl --kubeconfig=dev.conf get po
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:dev:dev" cannot list pods in the namespace "default"

$ kubectl -n dev --kubeconfig=dev.conf run nginx --image nginx --port 80 --restart=Never
$ kubectl -n dev --kubeconfig=dev.conf get po
NAME      READY     STATUS    RESTARTS   AGE
nginx     1/1       Running   0          39s

$ kubectl -n dev --kubeconfig=dev.conf logs -f nginx
10.244.102.64 - - [04/Jan/2018:06:42:36 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.47.0" "-"

$ kubectl -n dev --kubeconfig=dev.conf exec -ti nginx sh
Error from server (Forbidden): pods "nginx" is forbidden: User "system:serviceaccount:dev:dev" cannot create pods/exec in the namespace "dev"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment