> For the complete documentation index, see [llms.txt](https://docs.keeper.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keeper.io/keeperpam/jp/secrets-manager/integrations/kubernetes-external-secrets-operator.md).

# 外部シークレットオペレータ

KeeperシークレットマネージャーのシークレットをKubernetes外部シークレットオペレータと同期

![](https://859776093-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPL6k1aGsLiFiiJ3Y7zCl%2Fuploads%2Fgit-blob-25538147c47db407552cbef3904024c38468398d%2Fkubernetes-eso-header.jpg?alt=media)

## 概要 <a href="#overview" id="overview"></a>

[External Secrets Operator](https://charts.external-secrets.io)は、各種外部APIからシークレットを同期し、Kubernetesへ挿入します。本ページでは主にExternal Secretsのセットアップ手順と、KeeperボルトからKubernetesへのシークレット同期を取り扱います。

External Secrets Operatorのドキュメントは[こちら](https://external-secrets.io/latest/provider/keeper-security/)をご参照ください。

## 機能 <a href="#features" id="features"></a>

* External SecretsによるKeeperボルトからKubernetesへのシークレット同期
* 全ポッドからKeeperボルトのシークレットへのリアルタイムアクセス

## 要件 <a href="#prerequisites" id="prerequisites"></a>

本ページでは、KeeperシークレットマネージャーとKubernetes External Secrets Operatorの連携について取り扱います。本連携を利用するには、以下が必要です。

* Keeperシークレットマネージャーへのアクセス（[クイックスタートガイド](https://docs.keeper.io/keeperpam/jp/secrets-manager/quick-start-guide.md)をご参照ください）
  * Keeperのサブスクリプションでシークレットマネージャーアドオンが有効になっていること
  * シークレットマネージャーポリシーが有効なロールに所属していること
* シークレットが共有されているKeeper[シークレットマネージャーアプリケーション](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/terminology.md#application)
  * アプリケーションの作成手順については、[クイックスタートガイド](https://docs.keeper.io/pages/-MeRAVfQmDBzKQBC0f_c#2.-create-an-application)をご参照ください
  * アプリケーションにフォルダを共有すること (シークレットの取得のみであれば読み取り専用で十分。PushSecretを使用する場合のみ、フォルダに対するアプリケーションの権限を「編集可能」にする)
  * IPロックを無効にしたクライアントデバイスをアプリケーションに追加すること (ポッドはノード間を移動し、送信元IPアドレスが変わる場合があるため、IPロックされたデバイスは変更後に使用できなくなる)
* 初期化済みで、Base64文字列としてエクスポートしたKeeper[シークレットマネージャー構成](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/secrets-manager-configuration.md)。ワンタイムアクセストークン (例: `US:abc123...`) は External Secrets では使用不可
* 以下のコマンドがインストールされていること
  * [`helm`](https://helm.sh/)（Kubernetes向けパッケージマネージャー）
  * [`kubectl`](https://kubernetes.io/docs/reference/kubectl/)（Kubernetes向けコマンドラインツール）

## 設定 <a href="#setup" id="setup"></a>

### Helmで External Secrets をインストール <a href="#install-external-secrets-with-helm" id="install-external-secrets-with-helm"></a>

Helm で External Secrets をインストールするには、以下のコマンドを実行します。

```shell
helm repo add external-secrets https://charts.external-secrets.io

helm install external-secrets \
    external-secrets/external-secrets \
    -n external-secrets \
    --create-namespace
```

### Base64 KSM構成を格納する Kubernetes シークレットの作成 <a href="#create-kubernetes-secret-to-store-base64-ksm-config" id="create-kubernetes-secret-to-store-base64-ksm-config"></a>

デバイス用の[シークレットマネージャー構成](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/secrets-manager-configuration.md)を作成すると、接続トークン、暗号化キー、識別子、ドメイン情報を含むBase64 JSON文字列が得られます。これらはKeeperシークレットマネージャーAPIからのデータの認証と復号化に使用されます。

Base64 JSON 構成文字列は External Secrets によって設定され、Keeper Security への認証に使用されます。通常の Kubernetes シークレット内で定義します。

以下のコマンドを実行すると、Keeperシークレットマネージャーへの認証に使用する Kubernetes シークレットが作成されます。

{% code lineNumbers="true" %}

```yaml
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: ksm-config-secret # KSM構成を格納するk8sシークレットの名前
type: Opaque
data:
  ksm_config: "[REPLACE WITH YOUR BASE64 JSON string]"
EOF
```

{% endcode %}

{% hint style="info" icon="pencil-line" %}
**注** 上記コード例の2〜8行目はYAMLファイルに保存し、`kubectl apply` で適用できます。たとえば、2〜8行目を `secrets.yaml` に保存し、以下を実行します。
{% endhint %}

```bash
kubectl apply -f secret.yaml
```

### SecretStore の作成 <a href="#create-secretstore" id="create-secretstore"></a>

Base64 JSON 文字列を `ksm_config` に設定した Kubernetes シークレットを作成したら、SecretStore を作成できます。

以下のコマンドを実行すると、SecretStoreが作成されます。

<pre class="language-yaml" data-line-numbers data-full-width="false"><code class="lang-yaml"><strong>kubectl apply -f - &#x3C;&#x3C;EOF
</strong>apiVersion: external-secrets.io/v1 
kind: SecretStore
metadata:
<strong>  name: my-external-secrets-secretstore   # KSMから取得したシークレットを格納するSecretStoreの名前
</strong>spec:
  provider:
    keepersecurity:                       # SecretStoreプロバイダ名（本例ではKeeperSecurity）
<strong>      authRef:
</strong>        name: ksm-config-secret           # KSM構成を格納するk8sシークレットの名前
        key: ksm_config                   # KSM構成を格納するk8sシークレットのキー
      folderID: "[SHARED FOLDER UID]"     # レコードが保存されているKeeperSecurity共有フォルダのUID
                                          #   フォルダがKSMアプリケーションに共有されていることを確認
EOF
</code></pre>

{% hint style="info" %}
上記コード例では、ボルト内でレコードが保存されている共有フォルダの UID を `folderID` に指定します
{% endhint %}

{% hint style="info" %}
`ClusterSecretStore` の場合は、作成したシークレットの名前空間を `SecretAccessKeyRef` の `namespace` に指定してください
{% endhint %}

{% hint style="info" icon="pencil-line" %}
上記コード例の2〜13行目はYAMLファイルに保存し、`kubectl apply` で適用できます。たとえば、2〜13行目を `secretstore.yaml` に保存し、以下を実行します。
{% endhint %}

```bash
kubectl apply -f secretstore.yaml
```

### ExternalSecret の作成 <a href="#create-externalsecret" id="create-externalsecret"></a>

次に、ExternalSecret を作成します。

以下のコード例ではExternalSecretを作成し、指定レコードのログインおよびパスワードフィールドの値をKubernetesシークレットに格納します。これらのフィールドは `target.template.data` セクションで定義され、1時間ごとに更新されます。利用可能なフィールドの一覧は[こちら](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/field-record-types.md)をご参照ください。

{% code lineNumbers="true" fullWidth="false" %}

```yaml
kubectl apply -f - <<EOF
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
 name: ksm-external-secret
spec:
 refreshInterval: 1h               # External SecretsがKeeperからレコードを再取得する間隔
                                    #   Keeperでの変更は、この間隔内にKubernetesへ反映される
                                    #   更新のたびにKeeperへリクエストが送信されるため、大規模環境では極端に短い値を避ける
 secretStoreRef:                    # 上記で定義したSecretStoreへの参照（Keeper Security認証用）
   kind: SecretStore                # シークレットストアの種類（上記定義と同じ値）
   name: my-external-secrets-secretstore  

 dataFrom:                          # KSMから取得するレコードの指定
   - extract:
       key: "[RECORD UID]"          # シークレット取得元のKeeperレコードUID
 target:                            # 取得したシークレットの格納先
   name: my-external-secrets-values # 作成するk8sシークレットの名前
   creationPolicy: Owner            # k8sシークレットが存在しない場合に作成
   template:
     engineVersion: v2          
     data:
       username: "{{ .login }}"     # Keeper Securityのloginフィールド値を
                                    # k8sシークレットのusernameキーに格納
       password: "{{ .password }}"  # Keeper Securityのpasswordフィールド値を
                                    # k8sシークレットのpasswordキーに格納
EOF
```

{% endcode %}

{% hint style="info" %}
上記コード例では、"\[RECORD UID]" を対象レコードUIDに置き換えてください
{% endhint %}

{% hint style="info" %}
`name`、`phone`、`bankAccount` など単一の文字列値に対応しない複雑な[タイプ](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/field-record-types.md)では、External Secrets は完全な JSON 文字列を返します。JSON テンプレート関数でデコードしてください
{% endhint %}

{% hint style="info" icon="pencil-line" %}
上記コード例の2〜27行目はYAMLファイルに保存し、`kubectl apply` で適用できます。たとえば、2〜27行目を `externalsecret.yaml` に保存し、以下を実行します。
{% endhint %}

```bash
kubectl apply -f externalsecret.yaml
```

#### 動作 <a href="#behavior" id="behavior"></a>

* レコードと ExternalSecret の対応関係
  * `remoteRef.key` はレコードの UID に対応。代わりにレコードのタイトルを使用する場合は、SecretStore に `getByTitleFallback: true` を設定する (タイトルは、アプリケーションから参照できるレコード内で一意である必要がある)
  * `remoteRef.property` は以下のいずれかに対応
    * フィールド: フィールドにラベルがある場合はそのラベル、ない場合は[レコードのフィールドタイプ](https://docs.keeper.io/keeperpam/jp/secrets-manager/about/field-record-types.md) (例: login、password、url)
    * CustomFields: レコードのフィールドラベル
    * Files: ボルトに表示される添付ファイル名 (ファイルのタイトル)。ボルト内で添付ファイルの名前を変更した場合は新しい名前を指定する。元のファイル名は一致しない
    * 未指定の場合、レコード全体が JSON 形式で返される
  * `remoteRef.version` は現時点では未対応
* `dataFrom`
  * `find.path` は現時点では未対応
  * `find.name.regexp` はレコードのタイトルと照合される。一致した各レコードは、タイトルを名前とする1つのキーになり、レコード全体が JSON 形式で格納される (Kubernetes シークレットのキーに使用できない文字は「\_」になる)
  * `find.tags` は現時点では未対応

#### カスタムフィールドとファイル <a href="#custom-fields-and-files" id="custom-fields-and-files"></a>

カスタムフィールドとファイル添付では、JSONの解析は不要です。`property` に、カスタムフィールドのラベル、またはボルトに表示される添付ファイル名を指定します。

```yaml
kubectl apply -f - <<EOF
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: ksm-custom-and-files
spec:
  refreshInterval: 1h
  secretStoreRef:
    kind: SecretStore
    name: my-external-secrets-secretstore
  target:
    name: my-app-extras                # 作成するKubernetesシークレット
  data:
    - secretKey: api-key               # Kubernetesシークレット内のキー
      remoteRef:
        key: "[RECORD UID]"
        property: "api_key"            # カスタムフィールド: そのラベル
    - secretKey: app-file
      remoteRef:
        key: "[RECORD UID]"
        property: "config.json"        # 添付ファイル: ボルトに表示される名前
EOF
```

ポッドでは、カスタムフィールドを環境変数として、添付ファイルをファイルとして読み取れます。

```yaml
      env:
        - name: API_KEY
          valueFrom:
            secretKeyRef:
              name: my-app-extras
              key: api-key
      volumeMounts:
        - name: keeper-files
          mountPath: /etc/keeper       # 添付ファイルは /etc/keeper/app-file として表示される
          readOnly: true
  volumes:
    - name: keeper-files
      secret:
        secretName: my-app-extras
        items:
          - key: app-file
            path: app-file
```

バイナリの添付ファイル (キーストア、DER形式の証明書など) はバイト単位でそのままコピーされます。レコードのすべてのフィールド、カスタムフィールド、添付ファイルを一度に取得するには、`dataFrom: - extract: key: "[RECORD UID]"` を使用します。スペースなど Kubernetes シークレットのキーに使用できない文字は「\_」になります。また、Keeper内部の添付ファイルIDを保持する追加の `fileRef` キーは無視して問題ありません。

### 制限事項 <a href="#limitations" id="limitations"></a>

本プロバイダの利用には、以下の制限があります。

* KSM はレガシーの非型付きレコードでは動作しない
* KSM では `find.tags` によるタグ指定は利用できない
* 現時点では `find.path` は利用できない
* レコード内のフィールドラベル、カスタムフィールドラベル、添付ファイル名は、login、password、url などの標準フィールド名も含め、すべて一意である必要がある。2つが重複すると (例: ログインレコードに「password」というラベルのカスタムフィールドがある、同名の添付ファイルが2つある)、取得対象外のフィールドがあっても、レコード全体が「invalid Secret. Following keys are duplicated」で失敗する。ボルト内でいずれかの名前を変更すること

### プッシュシークレット <a href="#push-secrets" id="push-secrets"></a>

プッシュシークレットは、レコードタイプ `externalSecrets` のレコードを作成および更新します。

動作

* `selector`
* `secret.name`: プッシュ対象の Kubernetes シークレット名
* `data.match`
* `secretKey`: プッシュ対象となる選択済みシークレット内のキー
* `remoteRef.remoteKey`: リモートプロバイダ上に作成するシークレットとキー
  * 形式: SecretName/SecretKey

### PushSecret の作成 <a href="#create-pushsecret" id="create-pushsecret"></a>

KubernetesからKeeper Securityのレコードを作成するには、`Kind=PushSecret` が必要です。

<pre class="language-yaml" data-line-numbers data-full-width="false"><code class="lang-yaml"><strong>kubectl apply -f - &#x3C;&#x3C;EOF
</strong>apiVersion: external-secrets.io/v1alpha1
kind: PushSecret
metadata:
  name: example
spec:
  secretStoreRefs:
    - name: my-external-secrets-secretstore
      kind: SecretStore
  refreshInterval: "1h"
  deletionPolicy: Delete
  selector:
    secret:
      name: secret-name # プッシュ対象のk8sシークレット
  data:
    - match:
        secretKey: secret-key # プッシュ対象のk8sシークレット内キー
        remoteRef:
          remoteKey: remote-secret-name/remote-secret-key # "remote-secret-name"というレコードと"remote-secret-key"キーを作成
EOF
</code></pre>

{% hint style="info" icon="pencil-line" %}
上記コード例の2〜19行目はYAMLファイルに保存し、`kubectl apply` で適用できます。たとえば、2〜19行目を `pushsecret.yaml` に保存し、以下を実行します。
{% endhint %}

```bash
kubectl apply -f pushsecret.yaml
```

{% hint style="warning" %}
使用中のKSMアプリケーション内に、タイトル `remote-secret-name` のレコードが1件のみ存在することを確認してください
{% endhint %}

#### 制限事項 <a href="#limitations_1" id="limitations_1"></a>

* External Secrets はレコードの作成時に1つのフィールドを書き込み、以降は、レコードに既に存在するフィールドのみ更新できる。そのため、新規レコードに複数のキーをプッシュすることはできない
  * `login`/`username`、`password`、`url` の各キーでは、2つ目のキーはエラーなしでスキップされ、PushSecret は Synced と表示されたまま
  * それ以外のキーでは、PushSecret は「does not contain any custom field with label 」で失敗
* 複数の値をプッシュするには、値ごとに別のレコードへプッシュするか、先にレコード (タイプは `externalSecrets`、プッシュするすべてのフィールドを含む) を作成し、External Secrets が更新のみを行うようにする
* Kubernetes シークレットの変更は、次の `refreshInterval` でプッシュされる。すぐにプッシュするには、`kubectl annotate pushsecret <name> force-sync=$(date +%s) --overwrite` を実行する
* `deletionPolicy: Delete` の場合、PushSecret を削除すると、Keeper 内のレコードも削除される

### トラブルシューティング <a href="#troubleshooting" id="troubleshooting"></a>

* STATUS が Valid と表示される SecretStore は、形式が正しいことを示すだけで、Keeperへの接続は ExternalSecret が同期されるまで確認されない。KSM構成が無効な場合 (構成ではなくワンタイムトークンを指定した場合も) でも、Valid と表示される
* ExternalSecret にステータスがない、または SecretSyncedError と表示される場合、イベントには通常「could not get secret data from provider」としか表示されない。「no record matched \[record UID]」や「does not have any key matching \[field name]」などの実際の原因は、オペレータのログで確認できる。ログは以下のコマンドで取得する。

```bash
kubectl logs -n external-secrets deploy/external-secrets | grep <externalsecret-name>
```

* refreshInterval を待たずにすぐ再試行するには、以下のコマンドを実行する。

```bash
kubectl annotate externalsecret <name> force-sync=$(date +%s) --overwrite
```

* External Secrets をアンインストールする前に、ExternalSecret と PushSecret のオブジェクトを削除すること。削除しないと、それらの名前空間が Terminating のまま残る

## セットアップの確認 <a href="#verifying-setup" id="verifying-setup"></a>

[Kubernetes シークレット](#create-kubernetes-secret-to-store-base64-ksm-config)、[SecretStore](#create-secretstore)、[ExternalSecret](#create-externalsecret)の設定後、`kubectl get secrets` コマンドでシークレットを取得できます。

上記のコード例では、シークレット名は `my-external-secrets-values` で、以下のレコード値が格納されます。

```yaml
data:
       username: "{{ .login }}"                                      
       password: "{{ .password }}"
```

ログインとパスワードの値を取得するには、以下のコマンドを実行します。

```
$ kubectl get secret my-external-secrets-values -o jsonpath="{.data}"
{"password":"a2lsbCB5b3U=","username":"SSB3aWxs"}
```

上記の応答はエンコードされているため、デコードするには以下を実行します。

{% code fullWidth="false" %}

```
$ kubectl get secret my-external-secrets-values -o jsonpath="{.data.password}" | base64 --decode
pAs$w0rd
```

{% endcode %}

## まとめ <a href="#conclusion" id="conclusion"></a>

本ページでは、Kubernetes External Secrets Operatorを介したKeeperシークレットマネージャーとKubernetesの連携手順を取り扱いました。手順に従うことで、Keeperボルトに保存したシークレットをKubernetes環境へ同期できます。シークレットの安全な管理に加え、全ポッドからのリアルタイムアクセスも可能になります。

External Secretsオペレータのセットアップ、Kubernetesシークレット・SecretStore・ExternalSecretの作成など、本連携の要点となる手順を取り扱いました。設定が完了すれば、記載のコマンドで連携を確認し、格納したシークレットを取得できます。

KeeperシークレットマネージャーとKubernetesの統合により、Kubernetes上で動作するアプリケーションのセキュリティ基盤が強化されます。シークレット管理の基盤となり、運用効率とセキュリティ体制の向上に役立ちます。

コマンド例のプレースホルダは、ご利用環境の情報に置き換えてください。KubernetesでExternal Secretsを設定・管理する際は、必要に応じて本ページをご参照ください。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.keeper.io/keeperpam/jp/secrets-manager/integrations/kubernetes-external-secrets-operator.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
