ノート:

Kyvernoを使用して、ImagePullSecrets属性をKubernetesポッドに注入します

イントロダクション

Oracle Cloud Infrastructure Container Engine for Kubernetes (OKE)は、完全に管理されたスケーラブルで可用性の高いサービスであり、コンテナ化されたアプリケーションをクラウドにデプロイする際に使用できます。

Oracle Cloud Infrastructure Registry (コンテナ・レジストリまたはOCIRとも呼ばれる)は、本番ワークフローの開発を簡略化できる、Oracle管理のレジストリです。Container Registryを使用すると、開発者はコンテナ・イメージを簡単に格納、共有および管理できます。

OCIRにパブリックまたはプライベートのコンテナ・イメージ・リポジトリを作成できます:

OCIRプライベート・レジストリからイメージをプルするには、Kubernetesに資格証明が必要です。ポッド構成ファイル内のspec.imagePullSecrets属性は、ワーカー・ノードがレジストリからコンテナ・イメージをプルするために使用する資格証明を含むKubernetesシークレットのリストを指定します。

アプリケーションのマニフェストおよびデプロイメントを簡略化し、OCIRとの統合時にOKEクラスタ固有の構成の一部を分離するために、Kyvernoを使用できます。CNCFに基づくこのインキュベーション・プロジェクトでは、ポリシー定義を使用して、Kubernetesリソースを検証、変更、生成およびクリーン・アップできます。この製品を利用して、新しいポッドの作成時にKubernetes APIに送信するマニフェストを変換し、OCIRに格納されているコンテナ・イメージのプルに必要なimagePullSecrets属性を注入できます。

目的

前提条件

タスク1: Kyvernoのインストール

Kyverno Webページには、KubernetesクラスタにKyvernoをインストールするための2つの方法が説明されています。

このチュートリアルでは、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、ユーザー名およびパスワードを確認します:

    レジストリURLは、OCIリージョン・キー(<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. ポッドが正常に作成されたかどうかを検証します。

    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チャネルでより無料のラーニング・コンテンツにアクセスしてください。また、education.oracle.com/learning-explorerにアクセスして、Oracle Learning Explorerになります。

製品ドキュメントについては、Oracle Help Centerを参照してください。