쿠버네티스(kubernetes)/CKA 준비

[ITExam-CKA] 1. Kubernetes RBAC - ClusterRole과 ServiceAccount Binding 실습

토끼C 2025. 2. 5. 18:46
반응형

 

https://www.itexams.com/exam/CKA

 

CKA Exam - Free Questions and Answers - ITExams.com

 

www.itexams.com

ITExams에서 CKA 자격증 취득을 위한 무료 문제를 제공한다.

 

1번 문항에 대한 풀이 방법을 공유하고자 한다.

 

 

가장 먼저 아래처럼 context를 설정하라는 내용을 볼 수 있다.


SIMULATION -

Set configuration context: 

$ | kubectl config use-context k8s

 


 

쿠버네티스에서 클러스터를 관리할 때, 하나의 kubeconfig 파일에서 여러 개의 클러스터, 사용자, 네임스페이스를 설정할 수 있는데, 이러한 클러스터와 사용자 조합 컨텍스트(Context)라고 부른다. 쉽게 말하면 사용할 환경을 설정하는거다.

 

그래서 위의 내용은 결국 'k8s라는 이름의 context를 사용하겠다'는 것이다.

 

 

아래부터가 진짜 문제 내용이다.


[문제]

Context -
You have been asked to create a new ClusterRole for a deployment pipeline and bind it to a specific ServiceAccount scoped to a specific namespace.

Task -
Create a new ClusterRole named deployment-clusterrole, which only allows to create the following resource types:
✑ Deployment
✑ Stateful Set
✑ DaemonSet
Create a new ServiceAccount named cicd-token in the existing namespace app-team1.
Bind the new ClusterRole deployment-clusterrole to the new ServiceAccount cicd-token, limited to the namespace app-team1.

 


[해설]

새로운 ClusterRole을 만들고 특정 네임스페이스로 범위가 지정된 특정 ServiceAccount에 바인딩해라.

- ClusterRole 이름은 deployment-clusterrole로 지정한다.

- create만 허용하며 resource 타입은 Deployment, StatefulSet, DaemonSet이다.

- 새로운 ServiceAccount를 만들고 이름은 cicd-token으로 지정한다. 네임스페이스는 app-team1로 지정한다.

- 새로운 ClusterRole인 deployment-clusterrole을 만들어 새로운 ServiceAccount인 cicd-token에 바인딩해라.

- namespace는 app-team1로 제한한다.


[작업 목록]

1. ClusterRole 만들기

2. Namespace 만들기

3. ServiceAccount 만들기

4. Binding 하기

- 문제 내용을 보고, 어떤 작업을 수행해야 하는지 작업 목록을 정리했다.

 

 

시작에 앞서 kubectl 자동완성 명령어 설정방법이다.

https://tokkicine.tistory.com/33

 

쿠버네티스 kubectl 명령어 자동완성 설정하기

centOS 기준 bash-completion 라이브러리 설치하고, .bashrc 에 alias 및 설정 추가해주면 된다. 1. bash-completion 라이브러리 설치[user@LYJ ~]$ sudo yum install -y bash-completion  2. .bashrc 파일에 설정 추가source /usr/sh

tokkicine.tistory.com

 

 

1. ClusterRole 만들기

먼저 ClusterRole을 만든다. 샘플 없이 리소스를 만들때 꿀팁은 help 명렁어를 쓰는거다.

kubectl create [리소스명] --help

 

 

아래처럼 결과를 얻을 수 있다.

[user@LYJ test]$ k create clusterrole --help
Create a cluster role.

Examples:
  # Create a cluster role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
  kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods

  # Create a cluster role named "pod-reader" with ResourceName specified
  kubectl create clusterrole pod-reader --verb=get --resource=pods --resource-name=readablepod
--resource-name=anotherpod

  # Create a cluster role named "foo" with API Group specified
  kubectl create clusterrole foo --verb=get,list,watch --resource=rs.apps

  # Create a cluster role named "foo" with SubResource specified
  kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status

  # Create a cluster role name "foo" with NonResourceURL specified
  kubectl create clusterrole "foo" --verb=get --non-resource-url=/logs/*

  # Create a cluster role name "monitoring" with AggregationRule specified
  kubectl create clusterrole monitoring --aggregation-rule="rbac.example.com/aggregate-to-monitoring=true"

Options:
    --aggregation-rule=:
        An aggregation label selector for combining ClusterRoles.

    --allow-missing-template-keys=true:
        If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to
        golang and jsonpath output formats.

    --dry-run='none':
        Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
        sending it. If server strategy, submit server-side request without persisting the resource.

    --field-manager='kubectl-create':
        Name of the manager used to track field ownership.

    --non-resource-url=[]:
        A partial url that user should have access to.

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
        jsonpath-as-json, jsonpath-file).

    --resource=[]:
        Resource that the rule applies to

    --resource-name=[]:
        Resource in the white list that the rule applies to, repeat this flag for multiple items

    --save-config=false:
        If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will
        be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.

    --show-managed-fields=false:
        If true, keep the managedFields when printing objects in JSON or YAML format.

    --template='':
        Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format
        is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

    --validate='strict':
        Must be one of: strict (or true), warn, ignore (or false).              "true" or "strict" will use a schema to validate
        the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation
        is enabled on the api-server, but will fall back to less reliable client-side validation if not.                "warn" will
        warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled
        on the API server, and behave as "ignore" otherwise.            "false" or "ignore" will not perform any schema
        validation, silently dropping any unknown or duplicate fields.

    --verb=[]:
        Verb that applies to the resources contained in the rule

 

ClusterRole을 만들 때 조건은 아래 세개였다.

(1) 이름을 deployment-clusterrole로 한다.

(2) create만 허용한다.

(3) resource 타입은 Deployment, StatefulSet, DaemonSet이다.

 

help 명령어를 수행했을 때 Examples 부분에서 'verb'와 'resource'가 있는 예제를 고르면 된다.

 

난 가장 맨 위의 예제를 조건에 맞게 수정했다.

 kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods

 

 

위의 예제를 아래처럼 수정했다.

kubectl create clusterrole deploymnet-clusterrole --verb=create --resource=Deployment,StatefulSet,DaemonSet

위 명령어 수행으로 내가 정의한 4개의 작업 목록 중 1번 작업을 완료했다.

 

 

 

 

2. Namespace 만들기

네임스페이스를 왜 먼저 만드냐면 ServiceAccount를 app-team1이라는 네임스페이스에 정의해야 하기 때문이다.

네임스페이스는 특정한 작업 공간이라고 보면 된다.

 

네임스페이스도 --help 로 만드는 예제를 조회할 수 있지만, 대부분 굉장히 간단하다.

 

아래처럼 만들어주면 되고, namspace의 alias인 ns를 사용할 수 있다.

kubectl create ns app-team1

 

 

 

 

 

 

3. ServiceAccount 만들기

ServiceAccount는 이름처럼 그냥 계정이다. POD가 리소스와 상호 작용을 필요로 할때 서비스어카운트를 사용한다.

ServiceAccount도 똑같이 help 치면 된다. 리소스 생성하는 영역은 다 외우지 않아도 웬만하면 help 명령어로 넘어갈 수 있다.

 

serviceaccount의 alias는 sa로 다음처럼 만들 수 있다.

[user@LYJ test]$ k create sa --help
Create a service account with the specified name.

Aliases:
serviceaccount, sa

Examples:
  # Create a new service account named my-service-account
  kubectl create serviceaccount my-service-account

 

ServiceAccount를 만들때 조건은 아래 두개였다.

- 이름은 cicd-token으로 지정한다.

- 네임스페이스는 app-team1로 지정한다.

 

웬만하면 help 치면 되지만, 네임스페이스는 help 쳐도 같이 안 나온다......

이것도 많이 쓰니까 외우면 된다. 네임스페이스를 지정할때는 아래처럼 -n 옵션을 주면 된다.

kubectl create [생성할 리소스종류] [생성할 리소스명] -n [네임스페이스명]

 

삭제할 때도 똑같다. 네임스페이스 지정은 '-n' 옵션 기억하자.

kubectl delete [삭제할 리소스종류] [삭제할 리소스명] -n [네임스페이스명]

 

 

쨋든 그래서 조건 반영해서 아래 명령로 만들면 된다.

kubectl create sa cicd-token -n app-team1

 

 

 

 

 

4. Binding 하기

문제에는 바인드 하라고 나와있는데, 바인딩하는 방법도 create 명령어를 쓰면 된다. ClusterRoleBinding이라는 리소스를 만들면 된다.

 

Bind 조건으로는 아래 한 가지가 있었다.

- namespace는 app-team1로 제한한다.

 

이것도 help 치면 된다.

[user@LYJ test]$ k create clusterrolebinding --help
Create a cluster role binding for a particular cluster role.

Examples:
  # Create a cluster role binding for user1, user2, and group1 using the cluster-admin cluster role
  kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --user=user2 --group=group1

Options:
    --allow-missing-template-keys=true:
        If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to
        golang and jsonpath output formats.

    --clusterrole='':
        ClusterRole this ClusterRoleBinding should reference

    --dry-run='none':
        Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
        sending it. If server strategy, submit server-side request without persisting the resource.

    --field-manager='kubectl-create':
        Name of the manager used to track field ownership.

    --group=[]:
        Groups to bind to the clusterrole. The flag can be repeated to add multiple groups.

    -o, --output='':
        Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
        jsonpath-as-json, jsonpath-file).

    --save-config=false:
        If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will
        be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.

    --serviceaccount=[]:
        Service accounts to bind to the clusterrole, in the format <namespace>:<name>. The flag can be repeated to add
        multiple service accounts.

    --show-managed-fields=false:
        If true, keep the managedFields when printing objects in JSON or YAML format.

    --template='':
        Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format
        is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

    --user=[]:
        Usernames to bind to the clusterrole. The flag can be repeated to add multiple users.

    --validate='strict':
        Must be one of: strict (or true), warn, ignore (or false).              "true" or "strict" will use a schema to validate
        the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation
        is enabled on the api-server, but will fall back to less reliable client-side validation if not.                "warn" will
        warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled
        on the API server, and behave as "ignore" otherwise.            "false" or "ignore" will not perform any schema
        validation, silently dropping any unknown or duplicate fields.

Usage:
  kubectl create clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname]
[--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

 

우선 예제를 보면 유저 정하는 것과 그룹 정하는 것은 있는데, Example에는 서비스어카운트와 네임스페이스 정하는 건 없고, Option과 Usage 부분을 찾아보면 namespace:serviceaccount 형식으로 입력하라는 걸 확인할 수 있다.

 

참고해서 다음 명령어로 생성하면 된다.

 kubectl create clusterrolebinding deployment-clusterrolebinding --serviceaccount=app-team1:cicd-token

문제에서 바인딩 이름에 대한 조건은 없어서 내 맘대로 deployment-clusterrolebinding이라고 지정했다.

 

 

 


여기까지 문제 풀이 끝이다. 

 

 

요약하면 이렇다.

 

1. ClusterRole 만들기

kubectl create clusterrole deploymnet-clusterrole --verb=create --resource=Deployment,StatefulSet,DaemonSet

 

2. Namespace 만들기

kubectl create ns app-team1

 

 

3. ServiceAccount 만들기

kubectl create sa cicd-token -n app-team1

 

4. Binding 하기

 kubectl create clusterrolebinding deployment-clusterrolebinding --serviceaccount=app-team1:cicd-token
반응형