본문 바로가기

⭐ Kubernetes & EKS/RBAC (Role-Based Access Control)

클러스터 접근을 위한 사용자 생성 및 특정 NameSpace에 접근하도록 설정하기

# 클러스터 User 생성 및 특정 NamaSpace에만 접근하도록 설정하기

1. 유저 확인 및 롤 확인하기

- 일단 기본 템플릿은 아래와 같다.

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

- 특정 user에 대한 접근 템플릿

apiVersion: rbac.authorization.k8s.io/v1
# This role binding allows "dave" to read secrets in the "development" namespace.
# You need to already have a ClusterRole named "secret-reader".
kind: RoleBinding
metadata:
  name: read-secrets
  #
  # The namespace of the RoleBinding determines where the permissions are granted.
  # This only grants permissions within the "development" namespace.
  namespace: development
subjects:
- kind: User
  name: dave # Name is case sensitive
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: secret-reader
  apiGroup: rbac.authorization.k8s.io

- 일단 현재의 계정의 롤을 조회하면 아래와 같다.

롤 조회 명령어는 아래와 같다.

kubectl edit configmap aws-auth -n kube-system

- 롤을 조회하면 아래와 같은 결과가 나타나는데 AWS 같은 경우는 IAM과 연동되어 IAM의 arn 주소값을 그대로 사용하는 것을 확인 할 수 있다.

고로 AWS IAM 사용자는 별도의 계정을 생성하지 않고도 AWS를 통해서 EKS로 접근하게 되면 IAM 정보 기반으로 리소스에 접근을 시도한다.

apiVersion: v1
data:
  mapRoles: |
    - groups:
      - system:bootstrappers
      - system:nodes
      rolearn: arn:aws:iam::00000000000000:role/EKS-WorkerNode-Role
      username: system:node:{{EC2PrivateDNSName}}
  mapUsers: |
    - groups:
      - system:masters
      userarn: arn:aws:iam::000000000000:user/test_01
      userarn: arn:aws:iam::000000000000:user/test_02
      username: admin
kind: ConfigMap
metadata:
  creationTimestamp: "2022-06-15T04:47:43Z"
  name: aws-auth
  namespace: kube-system
  resourceVersion: "6187173"
  uid: 000000000000-0000-0000-00000000000

위와같이 설정을 하면 된다.

userarn과 username을 기반으로 접근 권한을 설정 할 수 있다.

2. 생성된 유저와 롤을 기반으로 네임 스페이스에 접근 권한을 설정해보자

- Role 조회 명령어

kubectl get role -n namespace_name

첫번째, 롤을 생성한다.

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: dev-was
  namespace: dev-was
rules:
  - apiGroups: ["", "extensions", "apps"]
    resources: ["deployments", "replicasets", "pods"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

두번째 롤도 함께 생성한다.

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: dev-batch
  namespace: dev-batch
rules:
  - apiGroups: ["*"]
    resources: ["*"]
    verbs: ["*"]

3. 생성한 Role을 RoleBinding하여 맵핑하기

- dev-was-rolebinding 생성하기

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: dev-was-rolebinding
  namespace: dev-was
subjects:
- kind: Group
  name: dev
roleRef:
  kind: Role
  name: dev-was
  apiGroup: rbac.authorization.k8s.io

- dev-batch-rolebinding 생성하기

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: dev-batch-rolebinding
  namespace: dev-batch
subjects:
- kind: Group
  name: dev
roleRef:
  kind: Role
  name: dev-batch
  apiGroup: rbac.authorization.k8s.io

- 이로써 특정 사용자에게 부여하기 위한 role과 rolebinding이 모두 생성 되었다.

조회를 해보면 아래와 같이 나오는것을 확인 할 수 있다.

- role 조회

:~/environment/role $ kubectl get role -A
NAMESPACE      NAME                                                CREATED AT
dev-batch      dev-batch                                           2023-07-27T06:20:49Z
dev-was        dev-was                                             2023-07-27T06:01:23Z

- rolebinding 조회

:~/environment/role $ kubectl get rolebinding -A                                                                                             
NAMESPACE      NAME                                                           ROLE                                                     AGE
dev-batch      dev-batch-rolebinding                                          Role/dev-batch                                           5m22s
dev-was        dev-was-rolebinding                                            Role/dev-was                                             7m15s

4. aws-auth Configmap에 적용하기

kubectl edit configmap aws-auth -n kube-system

위의 명령어로 조회 후 IAM으로 추가한 사용자를 등록해준다.

나는 여기서 test라는 IAM 유저를 생성하였고, test라는 유저를 dev-was와 dev-batch만 사용 가능하도록 등록 하겠다.

- aws auth 정보를 yaml 파일로 저장한다.

kubectl get configmaps aws-auth -n kube-system -o yaml > aws-auth.yaml

- 아래와 같이 계정을 추가해준다.

 

- Warning 메세지 출력 → 자동으로 수정 됐단다.

Warning: resource configmaps/aws-auth is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
configmap/aws-auth configured

5. 테스트하기

- 실제로 test 계정을 활용하여 EKS 클러스터에 접근하고, 위에서 설정한 NameSpace에만 접근이 가능한지 확인해보자.

- 여기서 주의해야할 점은 새로 생성한 계정의 자격증명으로 로그인을 해줘야 한다는 점이다.

자격증명이 존재하지 않을 시에는 새로 하나 만들고 만든 자격증명으로 리눅스나 접근지에서 자격증명을 수행 후 접근 하자.

- 접근 테스트 수행

[ec2-user@ip~]$ kubectl get pod -A
Error from server (Forbidden): pods is forbidden: User "dev_user2" cannot list resource "pods" in API group "" at the cluster scope

- 허용 가능한 NameSpace 접근 :: 접근가능

[ec2-user@test]$ kubectl get pod -n dev-was
No resources found in dev-was namespace.

- 예제로 nginx 웹서버를 설치하여 테스트

- nginx-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: dev-was
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: dev-batch
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

위에서 정의한것과 같이 접근 가능한 namespace인 dev-was와 dev-batch에 nginx 웹서버를 디플로이 해보자.

- 아래의 결과를 보면 정상적으로 nginx가 생성 되었고, 조회도 가능한것을 확인 할 수 있다.

[ec2-user@test]$ kubectl get pod -n dev-was
NAME                    READY   STATUS    RESTARTS   AGE
nginx-cbdccf466-8l2pz   1/1     Running   0          12s
[ec2-user@test]$ kubectl get pod -n dev-batch
NAME                    READY   STATUS    RESTARTS   AGE
nginx-cbdccf466-mkbsw   1/1     Running   0          20s

- 다른 조회 명령어로 조회하면 접근 거부 메세지가 뜬다.

[ec2-user@test]$ kubectl create ns test
Error from server (Forbidden): namespaces is forbidden: User "dev_user2" cannot create resource "namespaces" in API group "" at the cluster scope
[ec2-user@test]$ kubectl get ns
Error from server (Forbidden): namespaces is forbidden: User "dev_user2" cannot list resource "namespaces" in API group "" at the cluster scope
[ec2-user@test]$ kubectl get pod -n dev
Error from server (Forbidden): pods is forbidden: User "dev_user2" cannot list resource "pods" in API group "" in the namespace "dev"

위의 계정 이름이 test인 이유는 IAM 계정 이름이 test이기 때문이고, 자격증명이 정상적으로 수행되었다고 확인 할 수 있다.

마지막으로 권한 생성시 가장 중요한 것은 Cluster-Admin에 대한 권한을 아무에게나 부여해서는 안된다.

Cluster-Admin 권한은 모든 서비스를 실행 할 수 있으므로, 특정 관리자 및 꼭 필요한 사람에게만 부여 해야한다.

 

- 끝 -