참고:

Kyverno를 이용해 Kubernetes 포드에 ImagePullSecrets 속성 삽입

소개

Oracle Cloud Infrastructure Container Engine for Kubernetes(OKE)는 컨테이너형 애플리케이션을 클라우드에 배포하는 데 사용할 수 있는 확장 가능한 완전 관리형 고가용성 서비스입니다.

Oracle Cloud Infrastructure Registry(Container Registry 또는 OCIR이라고도 함)는 Oracle 관리 레지스트리로 운용 워크플로우에 대한 개발을 간소화할 수 있습니다. Container Registry를 사용하면 개발자가 컨테이너 이미지를 쉽게 저장, 공유 및 관리할 수 있습니다.

OCIR에서 공용 또는 전용 컨테이너 이미지 저장소를 생성할 수 있습니다.

OCIR 전용 레지스트리에서 이미지를 풀링하려면 Kubernetes에 인증서가 필요합니다. Pod 구성 파일의 spec.imagePullSecrets 속성은 작업자 노드가 레지스트리에서 컨테이너 이미지를 가져오는 데 사용해야 하는 인증서가 포함된 Kubernetes 암호 목록을 지정합니다.

응용 프로그램 매니페스트 및 배치를 단순화하고 OCIR과 통합할 때 OKE 클러스터 관련 구성 일부를 분리하기 위해 Kyverno를 사용할 수 있습니다. CNCF에서 이 인큐베이팅 프로젝트는 정책 정의를 사용하여 Kubernetes 리소스를 검증, 변경, 생성 및 정리할 수 있습니다. 새 POD를 생성하고 OCIR에 저장된 컨테이너 이미지를 추출하는 데 필요한 imagePullSecrets 속성을 삽입할 때 이 제품을 활용하여 Kubernetes API로 제출하는 매니페스트를 변경할 수 있습니다.

목표

필요 조건

작업 1: Kyverno 설치

Kyverno 웹 페이지는 Kubernetes 클러스터에 Kyverno를 설치하는 두 가지 방법을 설명합니다.

이 자습서에서는 Helm 차트를 사용하여 Kyverno를 설치하는 방법에 대해 집중적으로 다룰 것입니다.

작업 1.1: helm 설치

  1. 사용 중인 운영 체제에 따라 이 설명서를 살펴보고 helm를 설치합니다.

  2. 다음 명령을 실행하여 설치가 성공했는지 확인합니다.

    helm version
    # version.BuildInfo{Version:"v3.8.1", GitCommit:"5cb9af4b1b271d11d7a97a71df3ac337dd94ad37", GitTreeState:"clean", GoVersion:"go1.17.5"}
    

작업 1.2: 독립형 모드로 Kyverno 설치

  1. Kyverno Helm 저장소를 추가합니다.

    helm repo add kyverno https://kyverno.github.io/kyverno/
    # "kyverno" has been added to your repositories
    
  2. 차트의 새 저장소를 스캔합니다.

    helm repo update
    # Hang tight while we grab the latest from your chart repositories...
    # ...Successfully got an update from the "kyverno" chart repository
    # Update Complete. ⎈Happy Helming!⎈
    
  3. kyverno 네임스페이스에 Kyverno를 설치합니다.

    helm install kyverno kyverno/kyverno -n kyverno --create-namespace
    # NAME: kyverno
    # LAST DEPLOYED: Fri Aug 30 12:20:33 2023
    # NAMESPACE: kyverno
    # STATUS: deployed
    # REVISION: 1
    # NOTES:
    # Chart version: 3.0.1
    # Kyverno version: v1.10.0
    
    # Thank you for installing kyverno! Your release is named kyverno.
    
    # The following components have been installed in your cluster:
    # - CRDs
    # - Admission controller
    # - Reports controller
    # - Cleanup controller
    # - Background controller
    

작업 2: Kubernetes ImagePull 암호 생성

  1. 여기에 제공된 단계에 따라 사용자 Auth Token을 생성합니다. 인증 토큰 가져오기

  2. OCIR에 대한 사용자 액세스를 허용하도록 적절한 정책이 구성되었는지 확인합니다(저장소 액세스를 제어하는 정책).

  3. OCIR 레지스트리 URL, 유저 이름 및 암호를 확인합니다.

    레지스트리 URLOCI 지역 키를 기반으로 합니다. <region-key>.ocir.io

    예: OCI 피닉스 지역의 경우: phx.ocir.io

    사용자 이름테넌시 네임스페이스, oci 사용자 이름 및 IDP(사용된 경우): <tenancy-namespace>/<username> 또는 <tenancy-namespace>/oracleidentitycloudservice/<username>를 기반으로 합니다.

    예:

    axaxnpcrorw5/jdoe@acme.com 또는 axaxnpcrorw5/oracleidentitycloudservice/jdoe@acme.com

  4. 이름이 ocirsecret인 Kubernetes 암호를 생성합니다.

    kubectl create secret docker-registry ocirsecret --docker-server='<OCIR registry>' --docker-username='<username>' --docker-password='<auth-token>'
    

    예:

    kubectl create secret docker-registry ocirsecret --docker-server='phx.ocir.io' --docker-username='axaxnpcrorw5/jdoe@acme.com' --docker-password='cxOY5NL<AnBN}<123{_6'

작업 3: 필요한 Kyverno 정의 ClusterPolicies

  1. add-imagepullsecret.yaml라는 파일을 생성합니다.

  2. 아래 텍스트를 복사하여 파일에 붙여넣습니다.

    ---
    apiVersion: kyverno.io/v1
    kind: ClusterPolicy
    metadata:
      name: inject-imagepullsecret-to-namespace
      annotations:
        policies.kyverno.io/title: Clone imagePullSecret secret to new namespaces
        policies.kyverno.io/subject: Namespace
        policies.kyverno.io/description: >-
          ImagePullSecrets must be present in the same namespace as the pods using them.
          This policy monitors for new namespaces being created (except kube-system and kyverno),
          and automatically clones into the namespace the `ocirsecret` from the `default` namespace.
    spec:
      generateExisting: true
      rules:
      - name: inject-imagepullsecret-to-namespace
        match:
          any:
          - resources:
              kinds:
              - Namespace
        exclude:
          any:
          - resources:
              namespaces:
              - kube-system
              - kube-node-lease
              - kube-public
              - kyverno
        generate:
          apiVersion: v1
          kind: Secret
          name: ocirsecret
          namespace: "{{ request.object.metadata.name }}"
          synchronize: true
          clone:
            namespace: default
            name: ocirsecret
    ---
    apiVersion: kyverno.io/v1
    kind: ClusterPolicy
    metadata:
      name: add-imagepullsecrets
      annotations:
        policies.kyverno.io/title: Add imagePullSecrets
        policies.kyverno.io/subject: Pod
        policies.kyverno.io/description: >-
          Images coming from certain registries require authentication in order to pull them,
          and the kubelet uses this information in the form of an imagePullSecret to pull
          those images on behalf of your Pod. This policy searches pod spec for images coming from a
          registry which contains `phx.ocir.io/axaxnpcrorw5` and, if found, will mutate the Pod
          to add an imagePullSecret called `ocirsecret`.
    spec:
      rules:
      - name: add-imagepullsecret
        match:
          any:
          - resources:
              kinds:
              - Pod
        context:
        - name: images_in_ocir
          variable:
            jmesPath: "[request.object.spec.containers[*].image.contains(@, 'phx.ocir.io/axaxnpcrorw5'), request.object.spec.initContainers[*].image.contains(@, 'phx.ocir.io/axaxnpcrorw5')][]"
            default: []
        preconditions:
          all:
          - key: true
            operator: In
            value: "{{ images_in_ocir }}"
        mutate:
          patchStrategicMerge:
            spec:
              imagePullSecrets:
              - name: ocirsecret
    
  3. 기본 OCIR 주소 phx.ocir.io/axaxnpcrorw5을 사용 중인 주소로 바꿉니다.

  4. 클러스터에 ClusterPolicy을 생성하고 아래 명령을 실행하여 정책을 적용합니다.

    kubectl apply -f add-imagepullsecret.yaml
    # clusterpolicy.kyverno.io/inject-imagepullsecret-to-namespace created
    # clusterpolicy.kyverno.io/add-imagepullsecrets created
    

작업 4: 테스트

  1. 아래 텍스트를 포함하는 test-pod.yaml라는 파일을 생성합니다.

    참고: 위치 표시자의 전용 저장소에서 이미지의 URL을 채웁니다.

    ---
    apiVersion: v1
    kind: Namespace
    metadata:
      name: testns
    ---
    apiVersion: v1
    kind: Pod
    metadata:
      labels:
        run: testpod
      name: testpod
      namespace: testns
    spec:
      containers:
      - args:
        - /bin/sh
        - -c
        - sleep infinity
        image: <image_from_OCIR> # eg: phx.ocir.io/axaxnpcrorw5/nginx:latest
        name: test
        resources: {}
      dnsPolicy: ClusterFirst
      restartPolicy: Always
    
  2. 리소스 생성

    kubectl apply -f test-pod.yaml
    
  3. Pod가 성공적으로 생성되었는지 여부를 검증합니다.

    kubectl get pods -n testns
    # NAME      READY   STATUS    RESTARTS   AGE
    # testpod   1/1     Running   0          2m4s
    
  4. 암호가 기본 네임스페이스에서 새로 생성된 네임스페이스로 복제되었는지 검증합니다.

    kubectl get secret -n testns
    # NAME         TYPE                             DATA   AGE
    # ocirsecret   kubernetes.io/dockerconfigjson   1      2m56s
    

작업 5: 정리

  1. 테스트 중 생성된 로드 밸런서를 삭제합니다.

    kubectl delete -f test-pod.yaml
    
  2. 명령을 실행하여 Kyverno를 제거합니다.

    helm uninstall kyverno -n kyverno
    

승인

추가 학습 자원

docs.oracle.com/learn에서 다른 실습을 살펴보거나 Oracle Learning YouTube 채널에서 더 많은 무료 학습 콘텐츠에 액세스하십시오. 또한 Oracle Learning Explorer가 되려면 education.oracle.com/learning-explorer를 방문하십시오.

제품 설명서는 Oracle Help Center를 참조하십시오.