InfoGrab Docs

동적 Kubernetes 클러스터 등록

요약

동적 Kubernetes 클러스터 등록을 사용하면 개별 Kubernetes 서비스 인스턴스의 구성 파일을 수정하지 않고도 Teleport 클러스터에 연결된 Kubernetes 클러스터를 관리할 수 있습니다. 동적 Kubernetes 클러스터 등록은 여러 Kubernetes 서비스 인스턴스를 배포했거나 인프라의 Kubernetes 클러스터에 대한 접근을 정기적으로 재구성해야 할 때 유용합니다.

동적 Kubernetes 클러스터 등록을 사용하면 개별 Kubernetes 서비스 인스턴스의 구성 파일을 수정하지 않고도 Teleport 클러스터에 연결된 Kubernetes 클러스터를 관리할 수 있습니다.

동적 Kubernetes 클러스터 등록은 여러 Kubernetes 서비스 인스턴스를 배포했거나 인프라의 Kubernetes 클러스터에 대한 접근을 정기적으로 재구성해야 할 때 유용합니다.

이 가이드에서는 동적 Kubernetes 클러스터 등록을 설정하는 방법을 보여주고, tctl을 통해 Kubernetes 클러스터를 생성, 나열, 업데이트, 삭제하는 방법을 안내합니다.

작동 방식#

Teleport Kubernetes 서비스는 Teleport 사용자의 트래픽을 Kubernetes API 서버로 프록시하여 Kubernetes에 대한 접근을 관리하기 위해 패스워드 없는 인증, 역할 기반 접근 제어, 감사 로깅 및 기타 Teleport 기능을 활용할 수 있게 합니다.

이 단계에서는 Linux 호스트에 Teleport Kubernetes 서비스를 설치하고 Teleport 클러스터에 등록한 Kubernetes 클러스터에 접근하도록 구성합니다.

사전 요구사항#

  • A running Teleport cluster. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl and tsh clients.

    Installing `tctl` and `tsh` clients
    1. Determine the version of your Teleport cluster. The tctl and tsh clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at /v1/webapi/find and use a JSON query tool to obtain your cluster version. Replace with the web address of your Teleport Proxy Service:

      $ TELEPORT_DOMAIN=
      $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • Teleport Kubernetes 서비스를 설치할 Linux 호스트.

    Tip

teleport-kube-agent Helm 차트는 동적 Kubernetes 클러스터 등록을 지원하지 않습니다.

To check that you can connect to your Teleport cluster, sign in with tsh login, then verify that you can run tctl commands using your current credentials.

For example, run the following command, assigning to the domain name of the Teleport Proxy Service in your cluster and to your Teleport username:

$ tsh login --proxy= --user=
$ tctl status
# Cluster  (=teleport.url=)
# Version  (=teleport.version=)
# CA pin   (=presets.ca_pin=)

If you can connect to the cluster and run the tctl status command, you can use your current credentials to run subsequent tctl commands from your workstation. If you host your own Teleport cluster, you can also run tctl commands on the computer that hosts the Teleport Auth Service for full permissions.

1/3단계. Teleport Kubernetes 서비스 설정#

이 단계에서는 Linux 서버에 Teleport Kubernetes 서비스를 설치하는 방법을 보여줍니다.

조인 토큰 얻기#

조인 토큰을 생성하여 Teleport 클러스터와 새 Kubernetes 서비스 인스턴스 간의 신뢰를 설정합니다:

$ tctl tokens add --type=kube --ttl=1h --format=text
(=presets.tokens.first=)

토큰을 복사하여 Teleport Kubernetes 서비스를 실행할 때 사용할 수 있도록 안전한 곳에 보관합니다.

Teleport Kubernetes 서비스 설치#

Linux 호스트에 Teleport Kubernetes 서비스를 설치합니다:

To install a Teleport Agent on your Linux server:

The recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

  1. Assign to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///scripts/install.sh" | sudo bash
    

Teleport Kubernetes 서비스 구성#

Teleport Kubernetes 서비스를 실행할 호스트에서 다음 명령을 실행하여 Teleport 인스턴스의 기본 구성을 생성합니다. 에 Teleport Proxy 서비스 또는 Teleport Cloud 테넌트의 호스트와 포트를 할당하고 에 앞에서 생성한 조인 토큰을 할당합니다:

$ sudo teleport configure \
--proxy= \
--roles=kube \
--token= \
-o file

/etc/teleport.yaml의 구성 파일을 편집하여 다음을 포함합니다:

kubernetes_service:
  enabled: true
  resources:
  - labels:
      "*": "*"

이 구성은 Teleport 클러스터에 등록한 모든 Kubernetes 클러스터에 연결하도록 Kubernetes 서비스 인스턴스를 활성화합니다. resources[0].labels 필드에 와일드카드 패턴("*": "*")이 포함되어 있어 이 Kubernetes 서비스 인스턴스가 레이블 키나 값에 관계없이 모든 Kubernetes 클러스터 리소스에 연결할 수 있기 때문입니다.

Kubernetes 클러스터를 선택적으로 감시하기

와일드카드 문자 대신 특정 레이블 키와 값을 포함하여 특정 Kubernetes 클러스터 하위 집합을 감시하도록 Kubernetes 서비스 인스턴스를 구성할 수 있습니다:

resources:
- labels:
    "env": "prod"
    "region": "us-east-2"
- labels:
    "env": "test"
    "region": "us-west-1"

Kubernetes 서비스가 클러스터를 등록하려면 resources의 항목 중 어느 하나라도 클러스터의 레이블과 일치해야 합니다. resources의 항목이 일치하려면 해당 항목 내의 모든 labels 항목이 클러스터의 레이블과 일치해야 합니다.

예를 들어, env:prodregion:us-west-1 레이블을 가진 클러스터는 첫 번째 resources 항목의 env:prod 레이블만 일치하고 두 번째 resources 항목의 region:us-west-1 레이블만 일치하기 때문에 위 구성과 일치하지 않습니다.

그러나 env:testregion:us-west-1을 가진 클러스터는 두 번째 resources 항목에 주어진 두 레이블 모두 일치하기 때문에 일치합니다.

이 가이드의 뒷부분에서 동적 Kubernetes 클러스터 리소스를 생성할 때, 특정 Kubernetes 서비스 인스턴스만이 이를 감시하도록 레이블을 할당할 수 있습니다.

Teleport Kubernetes 서비스 실행#

Configure the Teleport Kubernetes Service to start automatically when the host boots up by creating a systemd service for it. The instructions depend on how you installed the Teleport Kubernetes Service.

You can check the status of the Teleport Kubernetes Service with systemctl status teleport and view its logs with journalctl -fu teleport.

2/3단계. 사용자 권한 부여#

Teleport에서 동적 Kubernetes 클러스터 등록을 활성화하려면 Teleport에 등록하려는 Kubernetes 클러스터에 접근할 수 있도록 사용자를 권한 부여해야 합니다. 이 단계에서 Teleport와 Kubernetes 클러스터 모두에서 이 접근을 구성합니다.

Kubernetes 클러스터에 대한 접근 허용#

접근을 활성화하려는 클러스터에 대한 올바른 Kubernetes 컨텍스트에 있는지 확인합니다.

사용 가능한 모든 컨텍스트를 검색합니다:

$ kubectl config get-contexts

CONTEXT_NAME을 선택한 컨텍스트 이름으로 바꿔 컨텍스트를 전환합니다:

$ kubectl config use-context CONTEXT_NAME
Switched to context CONTEXT_NAME

To authenticate to a Kubernetes cluster via Teleport, your Teleport user's roles must allow access as at least one Kubernetes user or group.

  1. Retrieve a list of your current user's Teleport roles. The example below requires the jq utility for parsing JSON:

    $ CURRENT_ROLES=$(tsh status -f json | jq -r '.active.roles | join ("\n")')
    
  2. Retrieve the Kubernetes groups your roles allow you to access:

    $ echo "$CURRENT_ROLES" | xargs -I{} tctl get roles/{} --format json | \
      jq '.[0].spec.allow.kubernetes_groups[]?'
    
  3. Retrieve the Kubernetes users your roles allow you to access:

    $ echo "$CURRENT_ROLES" | xargs -I{} tctl get roles/{} --format json | \
      jq '.[0].spec.allow.kubernetes_users[]?'
    
  4. If the output of one of the previous two commands is non-empty, your user can access at least one Kubernetes user or group, so you can proceed to the next step.

  5. If both lists are empty, create a Teleport role for the purpose of this guide that can view Kubernetes resources in your cluster.

    Create a file called kube-access.yaml with the following content:

    kind: role
    metadata:
      name: kube-access
    version: v7
    spec:
      allow:
        kubernetes_labels:
          '*': '*'
        kubernetes_resources:
          - kind: '*'
            namespace: '*'
            name: '*'
            verbs: ['*']
        kubernetes_groups:
        - viewers
      deny: {}
    
  6. Apply your changes:

    $ tctl create -f kube-access.yaml
    

    (!docs/pages/includes/create-role-using-web.mdx!)

  7. (!docs/pages/includes/add-role-to-user.mdx role="kube-access"!)

  8. Configure the viewers group in your Kubernetes cluster to have the built-in view ClusterRole. When your Teleport user assumes the kube-access role and sends requests to the Kubernetes API server, the Teleport Kubernetes Service impersonates the viewers group and proxies the requests.

    Create a file called viewers-bind.yaml with the following contents, binding the built-in view ClusterRole with the viewers group you enabled your Teleport user to access:

    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
      name: viewers-crb
    subjects:
    - kind: Group
      # Bind the group "viewers", corresponding to the kubernetes_groups we assigned our "kube-access" role above
      name: viewers
      apiGroup: rbac.authorization.k8s.io
    roleRef:
      kind: ClusterRole
      # "view" is a default ClusterRole that grants read-only access to resources
      # See: https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles
      name: view
      apiGroup: rbac.authorization.k8s.io
    
  9. Apply the ClusterRoleBinding with kubectl:

    $ kubectl apply -f viewers-bind.yaml
    

Kubernetes 클러스터 관리 권한 부여#

Teleport는 동적 kube_cluster 리소스를 통해 인프라의 Kubernetes 클러스터를 추적합니다. Teleport로 Kubernetes 클러스터에 대한 접근을 관리하려면 사용자에게 이러한 리소스를 관리할 수 있는 권한이 필요합니다.

이전 섹션에서 Teleport 클러스터에 등록된 모든 Kubernetes 클러스터에 접근할 수 있도록 사용자를 권한 부여했습니다. 이제 이 클러스터에 접근할 수 있으므로 관리할 수 있는 역할을 생성합니다.

다음 내용으로 kube-manager.yaml이라는 역할 정의를 생성합니다:

kind: role
metadata:
  name: kube-manager
spec:
  allow:
    rules:
    - resources:
      - kube_cluster
      verbs:
      - list
      - create
      - read
      - update
      - delete
version: v5

역할을 생성합니다:

$ tctl create -f kube-manager.yaml

Assign the kube-manager role to your Teleport user by running the appropriate commands for your authentication provider:

3/3단계. 동적 Kubernetes 클러스터 리소스 관리#

이제 Teleport 사용자에게 Kubernetes 클러스터 리소스를 관리할 권한이 있으므로, 리소스를 생성, 나열, 업데이트, 삭제하는 방법을 보여드립니다.

kubeconfig 생성#

이 섹션에서는 Teleport 클러스터가 Kubernetes 클러스터에 인증하는 데 사용할 Kubernetes Config 리소스(kubeconfig)를 생성합니다.

이 가이드의 앞부분에서 Teleport에 로그인했을 때, tsh가 Teleport 클러스터를 기반으로 한 Kubernetes 컨텍스트로 변경했을 수 있으므로, Teleport에 연결하려는 클러스터와 일치하도록 Kubernetes 컨텍스트를 업데이트해야 합니다:

$ kubectl config get-contexts
# CONTEXT_NAME을 선택한 컨텍스트에 할당합니다
$ kubectl config use-context CONTEXT_NAME

워크스테이션에서 kubeconfig를 생성하는 데 사용할 Teleport의 get-kubeconfig.sh 스크립트를 다운로드합니다:

$ curl -OL \
https://raw.githubusercontent.com/gravitational/teleport/v(=teleport.version=)/examples/k8s-auth/get-kubeconfig.sh

이 스크립트는 Kubernetes 파드를 가져오고 사용자, 그룹 및 기타 서비스 계정을 가장(impersonate)할 수 있는 Teleport Kubernetes 서비스용 서비스 계정을 생성합니다. Teleport Kubernetes 서비스는 이 서비스 계정을 사용하여 Kubernetes 클러스터의 리소스에 대한 접근을 관리합니다. 또한 스크립트는 서비스 계정 자격 증명을 저장하기 위해 클러스터에 Kubernetes Secret이 있는지 확인합니다.

get-kubeconfig.sh는 배포하는 리소스를 위해 teleport라는 네임스페이스를 생성하지만, 스크립트를 실행하는 셸에서 TELEPORT_NAMESPACE 환경 변수를 할당하여 다른 이름을 선택할 수 있습니다.

리소스를 생성한 후 get-kubeconfig.sh는 스크립트를 실행한 디렉터리의 kubeconfig라는 파일에 새 kubeconfig를 작성합니다.

get-kubeconfig.sh 스크립트를 실행합니다:

$ bash get-kubeconfig.sh

스크립트가 성공적이면 이 메시지가 표시됩니다:

Done!

생성된 kubeconfig 파일을 Teleport Proxy 서비스에 복사하라는 스크립트의 지시를 무시하세요. 다음 섹션에서 동적 kube_cluster 리소스를 생성할 때 kubeconfig 파일을 사용하는 방법을 보여드립니다.

Kubernetes 클러스터 리소스 생성#

kube_cluster.yaml이라는 파일에 다음 내용으로 kube_cluster 리소스를 정의합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
spec:
  kubeconfig: |

위 스니펫의 spec.kubeconfig 필드는 여러 줄 문자열을 시작합니다. 아래에 kubeconfig 파일의 내용을 그 값으로 포함합니다.

spec.kubeconfig는 base64로 인코딩된 문자열이어야 하므로, kubeconfig 파일을 base64로 변환한 다음 들여쓰기하고 다음 명령을 사용하여 kube_cluster.yaml 리소스 정의에 추가합니다:

$ printf "    %s" $(cat kubeconfig | base64) >> kube_cluster.yaml
kube_cluster에 레이블 추가하기

kube_cluster 리소스에 레이블을 추가하여 Teleport 역할이나 Kubernetes 서비스 인스턴스에서 특정 클러스터에 대한 접근을 관리할 수 있습니다.

레이블은 정적이거나 동적일 수 있습니다. 정적 레이블은 키/값 쌍입니다. 이 예제는 env=prodteam=dev 레이블을 정의합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
  labels:
    env: prod
    team: dev
spec:
  kubeconfig: KUBECONFIG

동적 레이블을 추가할 수도 있는데, 이는 Kubernetes 서비스 인스턴스가 레이블을 생성하기 위해 실행할 셸 명령을 정의합니다. 이렇게 하려면 kube_cluster 리소스의 spec.dynamic_labels 필드를 편집합니다.

이 예제는 python3 get_region.py 명령을 실행하여 Kubernetes 서비스가 배포된 지역을 가져오고 결과를 region 키에 할당합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
spec:
  kubeconfig: KUBECONFIG
  dynamic_labels:
    region:
      period: "24h"
      command: ["python3", "get_region.py"]

동적 레이블을 정의할 때 spec.dynamic_labels 필드 내의 키는 metadata.labels 필드 내의 키와 동일하게 동작하여 레이블의 키를 나타냅니다.

Kubernetes 서비스는 command에 주어진 명령을 period마다 실행하여 해당 키의 값을 얻습니다. command는 문자열 배열로 첫 번째 요소는 실행할 명령을, 이후 각 요소는 인수를 나타냅니다.

period는 숫자와 시간 단위를 포함하는 Go 지속 시간 문자열입니다. 지원되는 단위는 ns, us(또는 µs), ms, s, m, h입니다. 위 예제는 매일 명령을 실행하도록 Kubernetes 서비스를 구성합니다.

kube_cluster 리소스를 생성하려면 다음 명령을 실행합니다:

$ tctl create kube_cluster.yaml
kubernetes cluster "mycluster" has been created

새 Kubernetes 클러스터 접근#

Teleport Kubernetes 서비스 인스턴스는 새로 생성되거나 업데이트된 kube_cluster 리소스를 감시합니다. kube_cluster 리소스를 생성하면 해당 클러스터의 레이블을 추적하도록 구성된 Kubernetes 서비스 인스턴스가 해당 클러스터를 등록하고 Teleport를 통해 접근할 수 있게 합니다.

결과적으로 tsh kube ls를 실행하면 위에서 등록한 클러스터가 표시되어야 합니다:

$ tsh kube ls
 Kube Cluster Name Labels                      Selected
 ----------------- --------------------------- --------
 mycluster         teleport.dev/origin=dynamic

teleport.dev/origin=dynamic 레이블은 클러스터가 동적으로 등록되었음을 나타냅니다.

방금 등록한 클러스터에 로그인할 수도 있습니다:

$ tsh kube login mycluster
Logged into kubernetes cluster "mycluster". Try 'kubectl version' to test the
connection.

Kubernetes 클러스터 리소스 나열#

다음 명령으로 kube_cluster 리소스를 나열할 수 있습니다:

$ tctl get kube_clusters

Kubernetes 클러스터 리소스 업데이트#

앞에서 생성한 kube_cluster 리소스를 업데이트하려면 다음 명령을 실행하여 Auth 서비스의 백엔드에 존재하는 리소스를 텍스트 편집기에서 엽니다:

$ tctl edit kube_clusters/mycluster

kube_cluster에 레이블을 추가하도록 리소스를 편집합니다:

  kind: kube_cluster
  metadata:
    id: 9999999999999999999
    labels:
      teleport.dev/origin: dynamic
+     env: test
    name: mycluster
  spec:
    aws: {}
    azure: {}
    kubeconfig: KUBECONFIG
  version: v3

편집기에서 파일을 저장하고 닫아 변경사항을 적용합니다.

업데이트된 레이블이 표시되어야 합니다:

$ tsh kube ls
 Kube Cluster Name Labels                               Selected
 ----------------- ------------------------------------ --------
 mycluster         env=test teleport.dev/origin=dynamic *
Warning

업데이트된 kube_cluster 리소스의 레이블이 더 이상 Teleport Kubernetes 서비스 인스턴스가 감시하도록 구성된 레이블과 일치하지 않으면, 해당 인스턴스가 등록을 해제하고 Kubernetes 클러스터 프록시를 중지합니다.

Kubernetes 클러스터 리소스 삭제#

앞에서 생성한 kube_cluster 리소스를 삭제하려면 다음 명령을 실행합니다:

$ tctl rm kube_clusters/mycluster
kubernetes cluster "mycluster" has been deleted

이렇게 하면 Teleport에서 Kubernetes 클러스터 등록이 해제됩니다:

$ tsh kube ls
Kube Cluster Name Labels Selected
----------------- ------ --------

다음 단계#

이 가이드에서는 tctl을 사용하여 kube_cluster 리소스를 관리하는 방법을 보여드렸습니다. Teleport를 통해 Kubernetes 클러스터에 대한 접근을 관리하는 다른 방법에 관심이 있다면 다음 가이드를 확인하세요:

동적 Kubernetes 클러스터 등록

원문 보기
요약

동적 Kubernetes 클러스터 등록을 사용하면 개별 Kubernetes 서비스 인스턴스의 구성 파일을 수정하지 않고도 Teleport 클러스터에 연결된 Kubernetes 클러스터를 관리할 수 있습니다. 동적 Kubernetes 클러스터 등록은 여러 Kubernetes 서비스 인스턴스를 배포했거나 인프라의 Kubernetes 클러스터에 대한 접근을 정기적으로 재구성해야 할 때 유용합니다.

동적 Kubernetes 클러스터 등록을 사용하면 개별 Kubernetes 서비스 인스턴스의 구성 파일을 수정하지 않고도 Teleport 클러스터에 연결된 Kubernetes 클러스터를 관리할 수 있습니다.

동적 Kubernetes 클러스터 등록은 여러 Kubernetes 서비스 인스턴스를 배포했거나 인프라의 Kubernetes 클러스터에 대한 접근을 정기적으로 재구성해야 할 때 유용합니다.

이 가이드에서는 동적 Kubernetes 클러스터 등록을 설정하는 방법을 보여주고, tctl을 통해 Kubernetes 클러스터를 생성, 나열, 업데이트, 삭제하는 방법을 안내합니다.

작동 방식#

Teleport Kubernetes 서비스는 Teleport 사용자의 트래픽을 Kubernetes API 서버로 프록시하여 Kubernetes에 대한 접근을 관리하기 위해 패스워드 없는 인증, 역할 기반 접근 제어, 감사 로깅 및 기타 Teleport 기능을 활용할 수 있게 합니다.

이 단계에서는 Linux 호스트에 Teleport Kubernetes 서비스를 설치하고 Teleport 클러스터에 등록한 Kubernetes 클러스터에 접근하도록 구성합니다.

사전 요구사항#

  • A running Teleport cluster. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl and tsh clients.

    Installing `tctl` and `tsh` clients
    1. Determine the version of your Teleport cluster. The tctl and tsh clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at /v1/webapi/find and use a JSON query tool to obtain your cluster version. Replace with the web address of your Teleport Proxy Service:

      $ TELEPORT_DOMAIN=
      $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
      
    2. Follow the instructions for your platform to install tctl and tsh clients:

  • Teleport Kubernetes 서비스를 설치할 Linux 호스트.

    Tip

teleport-kube-agent Helm 차트는 동적 Kubernetes 클러스터 등록을 지원하지 않습니다.

To check that you can connect to your Teleport cluster, sign in with tsh login, then verify that you can run tctl commands using your current credentials.

For example, run the following command, assigning to the domain name of the Teleport Proxy Service in your cluster and to your Teleport username:

$ tsh login --proxy= --user=
$ tctl status
# Cluster  (=teleport.url=)
# Version  (=teleport.version=)
# CA pin   (=presets.ca_pin=)

If you can connect to the cluster and run the tctl status command, you can use your current credentials to run subsequent tctl commands from your workstation. If you host your own Teleport cluster, you can also run tctl commands on the computer that hosts the Teleport Auth Service for full permissions.

1/3단계. Teleport Kubernetes 서비스 설정#

이 단계에서는 Linux 서버에 Teleport Kubernetes 서비스를 설치하는 방법을 보여줍니다.

조인 토큰 얻기#

조인 토큰을 생성하여 Teleport 클러스터와 새 Kubernetes 서비스 인스턴스 간의 신뢰를 설정합니다:

$ tctl tokens add --type=kube --ttl=1h --format=text
(=presets.tokens.first=)

토큰을 복사하여 Teleport Kubernetes 서비스를 실행할 때 사용할 수 있도록 안전한 곳에 보관합니다.

Teleport Kubernetes 서비스 설치#

Linux 호스트에 Teleport Kubernetes 서비스를 설치합니다:

To install a Teleport Agent on your Linux server:

The recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

  1. Assign to your Teleport cluster hostname and port, but not the scheme (https://).

  2. Run your cluster's install script:

    $ curl "https:///scripts/install.sh" | sudo bash
    

Teleport Kubernetes 서비스 구성#

Teleport Kubernetes 서비스를 실행할 호스트에서 다음 명령을 실행하여 Teleport 인스턴스의 기본 구성을 생성합니다. 에 Teleport Proxy 서비스 또는 Teleport Cloud 테넌트의 호스트와 포트를 할당하고 에 앞에서 생성한 조인 토큰을 할당합니다:

$ sudo teleport configure \
--proxy= \
--roles=kube \
--token= \
-o file

/etc/teleport.yaml의 구성 파일을 편집하여 다음을 포함합니다:

kubernetes_service:
  enabled: true
  resources:
  - labels:
      "*": "*"

이 구성은 Teleport 클러스터에 등록한 모든 Kubernetes 클러스터에 연결하도록 Kubernetes 서비스 인스턴스를 활성화합니다. resources[0].labels 필드에 와일드카드 패턴("*": "*")이 포함되어 있어 이 Kubernetes 서비스 인스턴스가 레이블 키나 값에 관계없이 모든 Kubernetes 클러스터 리소스에 연결할 수 있기 때문입니다.

Kubernetes 클러스터를 선택적으로 감시하기

와일드카드 문자 대신 특정 레이블 키와 값을 포함하여 특정 Kubernetes 클러스터 하위 집합을 감시하도록 Kubernetes 서비스 인스턴스를 구성할 수 있습니다:

resources:
- labels:
    "env": "prod"
    "region": "us-east-2"
- labels:
    "env": "test"
    "region": "us-west-1"

Kubernetes 서비스가 클러스터를 등록하려면 resources의 항목 중 어느 하나라도 클러스터의 레이블과 일치해야 합니다. resources의 항목이 일치하려면 해당 항목 내의 모든 labels 항목이 클러스터의 레이블과 일치해야 합니다.

예를 들어, env:prodregion:us-west-1 레이블을 가진 클러스터는 첫 번째 resources 항목의 env:prod 레이블만 일치하고 두 번째 resources 항목의 region:us-west-1 레이블만 일치하기 때문에 위 구성과 일치하지 않습니다.

그러나 env:testregion:us-west-1을 가진 클러스터는 두 번째 resources 항목에 주어진 두 레이블 모두 일치하기 때문에 일치합니다.

이 가이드의 뒷부분에서 동적 Kubernetes 클러스터 리소스를 생성할 때, 특정 Kubernetes 서비스 인스턴스만이 이를 감시하도록 레이블을 할당할 수 있습니다.

Teleport Kubernetes 서비스 실행#

Configure the Teleport Kubernetes Service to start automatically when the host boots up by creating a systemd service for it. The instructions depend on how you installed the Teleport Kubernetes Service.

You can check the status of the Teleport Kubernetes Service with systemctl status teleport and view its logs with journalctl -fu teleport.

2/3단계. 사용자 권한 부여#

Teleport에서 동적 Kubernetes 클러스터 등록을 활성화하려면 Teleport에 등록하려는 Kubernetes 클러스터에 접근할 수 있도록 사용자를 권한 부여해야 합니다. 이 단계에서 Teleport와 Kubernetes 클러스터 모두에서 이 접근을 구성합니다.

Kubernetes 클러스터에 대한 접근 허용#

접근을 활성화하려는 클러스터에 대한 올바른 Kubernetes 컨텍스트에 있는지 확인합니다.

사용 가능한 모든 컨텍스트를 검색합니다:

$ kubectl config get-contexts

CONTEXT_NAME을 선택한 컨텍스트 이름으로 바꿔 컨텍스트를 전환합니다:

$ kubectl config use-context CONTEXT_NAME
Switched to context CONTEXT_NAME

To authenticate to a Kubernetes cluster via Teleport, your Teleport user's roles must allow access as at least one Kubernetes user or group.

  1. Retrieve a list of your current user's Teleport roles. The example below requires the jq utility for parsing JSON:

    $ CURRENT_ROLES=$(tsh status -f json | jq -r '.active.roles | join ("\n")')
    
  2. Retrieve the Kubernetes groups your roles allow you to access:

    $ echo "$CURRENT_ROLES" | xargs -I{} tctl get roles/{} --format json | \
      jq '.[0].spec.allow.kubernetes_groups[]?'
    
  3. Retrieve the Kubernetes users your roles allow you to access:

    $ echo "$CURRENT_ROLES" | xargs -I{} tctl get roles/{} --format json | \
      jq '.[0].spec.allow.kubernetes_users[]?'
    
  4. If the output of one of the previous two commands is non-empty, your user can access at least one Kubernetes user or group, so you can proceed to the next step.

  5. If both lists are empty, create a Teleport role for the purpose of this guide that can view Kubernetes resources in your cluster.

    Create a file called kube-access.yaml with the following content:

    kind: role
    metadata:
      name: kube-access
    version: v7
    spec:
      allow:
        kubernetes_labels:
          '*': '*'
        kubernetes_resources:
          - kind: '*'
            namespace: '*'
            name: '*'
            verbs: ['*']
        kubernetes_groups:
        - viewers
      deny: {}
    
  6. Apply your changes:

    $ tctl create -f kube-access.yaml
    

    (!docs/pages/includes/create-role-using-web.mdx!)

  7. (!docs/pages/includes/add-role-to-user.mdx role="kube-access"!)

  8. Configure the viewers group in your Kubernetes cluster to have the built-in view ClusterRole. When your Teleport user assumes the kube-access role and sends requests to the Kubernetes API server, the Teleport Kubernetes Service impersonates the viewers group and proxies the requests.

    Create a file called viewers-bind.yaml with the following contents, binding the built-in view ClusterRole with the viewers group you enabled your Teleport user to access:

    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
      name: viewers-crb
    subjects:
    - kind: Group
      # Bind the group "viewers", corresponding to the kubernetes_groups we assigned our "kube-access" role above
      name: viewers
      apiGroup: rbac.authorization.k8s.io
    roleRef:
      kind: ClusterRole
      # "view" is a default ClusterRole that grants read-only access to resources
      # See: https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles
      name: view
      apiGroup: rbac.authorization.k8s.io
    
  9. Apply the ClusterRoleBinding with kubectl:

    $ kubectl apply -f viewers-bind.yaml
    

Kubernetes 클러스터 관리 권한 부여#

Teleport는 동적 kube_cluster 리소스를 통해 인프라의 Kubernetes 클러스터를 추적합니다. Teleport로 Kubernetes 클러스터에 대한 접근을 관리하려면 사용자에게 이러한 리소스를 관리할 수 있는 권한이 필요합니다.

이전 섹션에서 Teleport 클러스터에 등록된 모든 Kubernetes 클러스터에 접근할 수 있도록 사용자를 권한 부여했습니다. 이제 이 클러스터에 접근할 수 있으므로 관리할 수 있는 역할을 생성합니다.

다음 내용으로 kube-manager.yaml이라는 역할 정의를 생성합니다:

kind: role
metadata:
  name: kube-manager
spec:
  allow:
    rules:
    - resources:
      - kube_cluster
      verbs:
      - list
      - create
      - read
      - update
      - delete
version: v5

역할을 생성합니다:

$ tctl create -f kube-manager.yaml

Assign the kube-manager role to your Teleport user by running the appropriate commands for your authentication provider:

3/3단계. 동적 Kubernetes 클러스터 리소스 관리#

이제 Teleport 사용자에게 Kubernetes 클러스터 리소스를 관리할 권한이 있으므로, 리소스를 생성, 나열, 업데이트, 삭제하는 방법을 보여드립니다.

kubeconfig 생성#

이 섹션에서는 Teleport 클러스터가 Kubernetes 클러스터에 인증하는 데 사용할 Kubernetes Config 리소스(kubeconfig)를 생성합니다.

이 가이드의 앞부분에서 Teleport에 로그인했을 때, tsh가 Teleport 클러스터를 기반으로 한 Kubernetes 컨텍스트로 변경했을 수 있으므로, Teleport에 연결하려는 클러스터와 일치하도록 Kubernetes 컨텍스트를 업데이트해야 합니다:

$ kubectl config get-contexts
# CONTEXT_NAME을 선택한 컨텍스트에 할당합니다
$ kubectl config use-context CONTEXT_NAME

워크스테이션에서 kubeconfig를 생성하는 데 사용할 Teleport의 get-kubeconfig.sh 스크립트를 다운로드합니다:

$ curl -OL \
https://raw.githubusercontent.com/gravitational/teleport/v(=teleport.version=)/examples/k8s-auth/get-kubeconfig.sh

이 스크립트는 Kubernetes 파드를 가져오고 사용자, 그룹 및 기타 서비스 계정을 가장(impersonate)할 수 있는 Teleport Kubernetes 서비스용 서비스 계정을 생성합니다. Teleport Kubernetes 서비스는 이 서비스 계정을 사용하여 Kubernetes 클러스터의 리소스에 대한 접근을 관리합니다. 또한 스크립트는 서비스 계정 자격 증명을 저장하기 위해 클러스터에 Kubernetes Secret이 있는지 확인합니다.

get-kubeconfig.sh는 배포하는 리소스를 위해 teleport라는 네임스페이스를 생성하지만, 스크립트를 실행하는 셸에서 TELEPORT_NAMESPACE 환경 변수를 할당하여 다른 이름을 선택할 수 있습니다.

리소스를 생성한 후 get-kubeconfig.sh는 스크립트를 실행한 디렉터리의 kubeconfig라는 파일에 새 kubeconfig를 작성합니다.

get-kubeconfig.sh 스크립트를 실행합니다:

$ bash get-kubeconfig.sh

스크립트가 성공적이면 이 메시지가 표시됩니다:

Done!

생성된 kubeconfig 파일을 Teleport Proxy 서비스에 복사하라는 스크립트의 지시를 무시하세요. 다음 섹션에서 동적 kube_cluster 리소스를 생성할 때 kubeconfig 파일을 사용하는 방법을 보여드립니다.

Kubernetes 클러스터 리소스 생성#

kube_cluster.yaml이라는 파일에 다음 내용으로 kube_cluster 리소스를 정의합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
spec:
  kubeconfig: |

위 스니펫의 spec.kubeconfig 필드는 여러 줄 문자열을 시작합니다. 아래에 kubeconfig 파일의 내용을 그 값으로 포함합니다.

spec.kubeconfig는 base64로 인코딩된 문자열이어야 하므로, kubeconfig 파일을 base64로 변환한 다음 들여쓰기하고 다음 명령을 사용하여 kube_cluster.yaml 리소스 정의에 추가합니다:

$ printf "    %s" $(cat kubeconfig | base64) >> kube_cluster.yaml
kube_cluster에 레이블 추가하기

kube_cluster 리소스에 레이블을 추가하여 Teleport 역할이나 Kubernetes 서비스 인스턴스에서 특정 클러스터에 대한 접근을 관리할 수 있습니다.

레이블은 정적이거나 동적일 수 있습니다. 정적 레이블은 키/값 쌍입니다. 이 예제는 env=prodteam=dev 레이블을 정의합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
  labels:
    env: prod
    team: dev
spec:
  kubeconfig: KUBECONFIG

동적 레이블을 추가할 수도 있는데, 이는 Kubernetes 서비스 인스턴스가 레이블을 생성하기 위해 실행할 셸 명령을 정의합니다. 이렇게 하려면 kube_cluster 리소스의 spec.dynamic_labels 필드를 편집합니다.

이 예제는 python3 get_region.py 명령을 실행하여 Kubernetes 서비스가 배포된 지역을 가져오고 결과를 region 키에 할당합니다:

kind: kube_cluster
version: v3
metadata:
  name: mycluster
spec:
  kubeconfig: KUBECONFIG
  dynamic_labels:
    region:
      period: "24h"
      command: ["python3", "get_region.py"]

동적 레이블을 정의할 때 spec.dynamic_labels 필드 내의 키는 metadata.labels 필드 내의 키와 동일하게 동작하여 레이블의 키를 나타냅니다.

Kubernetes 서비스는 command에 주어진 명령을 period마다 실행하여 해당 키의 값을 얻습니다. command는 문자열 배열로 첫 번째 요소는 실행할 명령을, 이후 각 요소는 인수를 나타냅니다.

period는 숫자와 시간 단위를 포함하는 Go 지속 시간 문자열입니다. 지원되는 단위는 ns, us(또는 µs), ms, s, m, h입니다. 위 예제는 매일 명령을 실행하도록 Kubernetes 서비스를 구성합니다.

kube_cluster 리소스를 생성하려면 다음 명령을 실행합니다:

$ tctl create kube_cluster.yaml
kubernetes cluster "mycluster" has been created

새 Kubernetes 클러스터 접근#

Teleport Kubernetes 서비스 인스턴스는 새로 생성되거나 업데이트된 kube_cluster 리소스를 감시합니다. kube_cluster 리소스를 생성하면 해당 클러스터의 레이블을 추적하도록 구성된 Kubernetes 서비스 인스턴스가 해당 클러스터를 등록하고 Teleport를 통해 접근할 수 있게 합니다.

결과적으로 tsh kube ls를 실행하면 위에서 등록한 클러스터가 표시되어야 합니다:

$ tsh kube ls
 Kube Cluster Name Labels                      Selected
 ----------------- --------------------------- --------
 mycluster         teleport.dev/origin=dynamic

teleport.dev/origin=dynamic 레이블은 클러스터가 동적으로 등록되었음을 나타냅니다.

방금 등록한 클러스터에 로그인할 수도 있습니다:

$ tsh kube login mycluster
Logged into kubernetes cluster "mycluster". Try 'kubectl version' to test the
connection.

Kubernetes 클러스터 리소스 나열#

다음 명령으로 kube_cluster 리소스를 나열할 수 있습니다:

$ tctl get kube_clusters

Kubernetes 클러스터 리소스 업데이트#

앞에서 생성한 kube_cluster 리소스를 업데이트하려면 다음 명령을 실행하여 Auth 서비스의 백엔드에 존재하는 리소스를 텍스트 편집기에서 엽니다:

$ tctl edit kube_clusters/mycluster

kube_cluster에 레이블을 추가하도록 리소스를 편집합니다:

  kind: kube_cluster
  metadata:
    id: 9999999999999999999
    labels:
      teleport.dev/origin: dynamic
+     env: test
    name: mycluster
  spec:
    aws: {}
    azure: {}
    kubeconfig: KUBECONFIG
  version: v3

편집기에서 파일을 저장하고 닫아 변경사항을 적용합니다.

업데이트된 레이블이 표시되어야 합니다:

$ tsh kube ls
 Kube Cluster Name Labels                               Selected
 ----------------- ------------------------------------ --------
 mycluster         env=test teleport.dev/origin=dynamic *
Warning

업데이트된 kube_cluster 리소스의 레이블이 더 이상 Teleport Kubernetes 서비스 인스턴스가 감시하도록 구성된 레이블과 일치하지 않으면, 해당 인스턴스가 등록을 해제하고 Kubernetes 클러스터 프록시를 중지합니다.

Kubernetes 클러스터 리소스 삭제#

앞에서 생성한 kube_cluster 리소스를 삭제하려면 다음 명령을 실행합니다:

$ tctl rm kube_clusters/mycluster
kubernetes cluster "mycluster" has been deleted

이렇게 하면 Teleport에서 Kubernetes 클러스터 등록이 해제됩니다:

$ tsh kube ls
Kube Cluster Name Labels Selected
----------------- ------ --------

다음 단계#

이 가이드에서는 tctl을 사용하여 kube_cluster 리소스를 관리하는 방법을 보여드렸습니다. Teleport를 통해 Kubernetes 클러스터에 대한 접근을 관리하는 다른 방법에 관심이 있다면 다음 가이드를 확인하세요: