Kubernetes 이야기

Service Account 권한 설정 및 kube config 본문

Kubernetes/일반

Service Account 권한 설정 및 kube config

kmaster 2022. 4. 4. 22:10
반응형

Kubernetes에서 Service Account를 만들고 해당 account에 적당한 권한을 부여하는 작업은 매우 중요하다.

 

실제 만드는 과정을 살펴보자.

 

1. Service Account 생성

apiVersion: v1
kind: ServiceAccount
metadata:
  name: dev-user
  namespace: demo

2. Role 생성

생성한 Service Account에 부여할 Role 을 생성한다.

# 개발에 필요한 모든 권한이 있는 Role
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: demo
  name: deployment-role
rules:
- apiGroups: ["", "extensions", "apps"]
  resources: ["deployments", "replicasets", "pods", "services", "ingresses"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] # ["*"] 와 같다.

3. RoleBinding 생성

생성한 Role을 service account에게 부여한다.

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: deployment-rolebinding
  namespace: demo
subjects:
- kind: ServiceAccount
  name: dev-user
  namespace: demo
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: deployment-role

4. kube config를 만들기 위해 token과 certificate 인증서 정보를 조회한다.

export NAMESPACE="demo"
export K8S_USER="demo-user"
# service account token 확인
kubectl -n ${NAMESPACE} describe secret $(kubectl -n ${NAMESPACE} get secret | (grep ${K8S_USER} || echo "$_") | awk '{print $1}') | grep token: | awk '{print $2}'\n
# certificate data 확인
kubectl  -n ${NAMESPACE} get secret `kubectl -n ${NAMESPACE} get secret | (grep ${K8S_USER} || echo "$_") | awk '{print $1}'` -o "jsonpath={.data['ca\.crt']}"

5. ~/.kube/config

# dev-user config파일
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUM1ekNDQWMrZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjR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HNQcFd4LzFJT2JjdWFjWlRDV2U0bmJFUk1OdXFVR09DMUJiM25jaExEVQp0VHJkT1VxUGQyZ0pDaDJZMmJ0NGQ5MHZmVENWOHNqOXloU0pnVXNMQitJdmRjeVNiTVM0T1VmcC92SmdMek9GCisyejBXMmpHUmdaWXYycXV1SW9lRm4zdW1wYXd1ZTh6YVZnOAotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
    server: https://127.0.0.1:39141
  name: mycluster

contexts:
- context:
    cluster: mycluster
    namespace: demo
    user: dev-user
  name: demo

current-context: demo
kind: Config
preferences: {}

users:
- name: dev-user
  user:
    token: eyJhbGciOiJSUzI1NiIsImtpZCI6IkIwN0F0SzJnNXhoU0NtU09UemU4ZlJ1TUpKdUUyZ1laYng2UktqVTRsZjgifQ.eyJpc3MiOiJrdWJ이하 생략

 

이제 config 파일을 적용 후 권한에 맞게 설정되었는지 확인해 보자.

# kubectl get po -n default : demo namespace만 권한이 있으니 오류
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "pods" in API group "" in the namespace "default"

#  cat <<EOF | kubectl create -n demo -f -
apiVersion: v1
kind: Pod
metadata:
  name: demo
spec:
  containers:
    - name: nginx
      image: nginx
      ports:
        - containerPort: 80
      resources:
        limits:
          memory: '1Gi'
          cpu: '800m'
        requests:
          memory: '700Mi'
          cpu: '400m'
EOF
pod/init-demo created


# kubectl get po -n demo
NAME   READY   STATUS    RESTARTS   AGE
demo   1/1     Running   0          12s

# kubectl get all -n demo ( resource 권한이 없는 것들은 조회가 안된다. )
NAME       READY   STATUS    RESTARTS   AGE
pod/demo   1/1     Running   0          37s
Error from server (Forbidden): replicationcontrollers is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "replicationcontrollers" in API group "" in the namespace "demo"
Error from server (Forbidden): daemonsets.apps is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "daemonsets" in API group "apps" in the namespace "demo"
Error from server (Forbidden): statefulsets.apps is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "statefulsets" in API group "apps" in the namespace "demo"
Error from server (Forbidden): horizontalpodautoscalers.autoscaling is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "horizontalpodautoscalers" in API group "autoscaling" in the namespace "demo"
Error from server (Forbidden): cronjobs.batch is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "cronjobs" in API group "batch" in the namespace "demo"
Error from server (Forbidden): jobs.batch is forbidden: User "system:serviceaccount:demo:dev-user" cannot list resource "jobs" in API group "batch" in the namespace "demo"

 

만약, dev-user에게 모든 Namespace의 관리자 권한 (모든 권한)을 주고자 하는경우에는 아래와 같이 cluster-admin 권한을 주면 된다.

kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: admin-all-cluster
subjects:
- kind: ServiceAccount
  name: dev-user
  namespace: demo
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
반응형

'Kubernetes > 일반' 카테고리의 다른 글

Bare metal VS VM Kubernetes  (0) 2022.04.09
Vertical Pod Autoscaler (VPA)  (0) 2022.04.09
PodNodeSelector  (0) 2022.04.02
Pod 스케줄링  (0) 2022.04.02
Kubernetes Pod Eviction  (0) 2022.04.02
Comments