# コード例

## エコー入力 <a href="#echo-inputs" id="echo-inputs"></a>

以下のポストローテーション後スクリプトの例では、入力パラメータを様々な言語とプラットフォームでエコーしています。print文の出力はKeeperゲートウェイのログファイルで確認できます。

* [Bash](#bash)
* [PowerShell](#powershell)
* [KeeperシークレットマネージャーSDK](#keepershkurettomanjsdk-no)

### Bash

注: この例では、 JSONを解析するために[jq](https://stedolan.github.io/jq/)がインストールされている必要があります。このコードをPAMスクリプトとして添付してローテーションを実行します。出力はゲートウェイのログファイルに含まれます。

{% code title="decode-and-echo.sh" %}

```bash
#!/bin/bash

# Base64エンコードされたJSON入力を読み込み、デコードする
decoded_json=$(cat | base64 --decode)

# Base64エンコードされている「records」フィールドを抽出し、別途デコードする
records_base64=$(echo "$decoded_json" | jq -r '.records')

# Base64形式の「records」フィールドをデコードし、JSONを整形して表示する
decoded_records=$(echo "$records_base64" | base64 --decode | jq '.')

# デコード済みの「records」に置き換えたJSON全体を出力する
echo "$decoded_json" | jq --argjson records "$decoded_records" '.records = $records'
```

{% endcode %}

### PowerShell

以下のコードをPAMスクリプトとして添付し、ローテーションを実行します。Keeperゲートウェイのログファイルに出力が含まれます。このスクリプトは入力をそのままエコーします。

```powershell
Begin {
    # パイプライン内の最初の項目が処理される前に一度だけ実行されます
}

Process {
    # エラーが発生した場合に処理を停止します。
    # 設定しない場合、結果は True となり、問題がなかったものとして扱われます。
    $ErrorActionPreference = "Stop"

    # パイプラインの各オブジェクトごとに一度ずつ実行されます
    $JSON = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($_))
    $Params = ($JSON | ConvertFrom-Json)

    Write-Output "providerRecordUid=$($Params.providerRecordUid)"
    Write-Output "resourceRecordUid=$($Params.resourceRecordUid)"
    Write-Output "userRecordUid=$($Params.userRecordUid)"
    Write-Output "newPassword=$($Params.newPassword)"
    Write-Output "oldPassword=$($Params.oldPassword)"
    Write-Output "user=$($Params.user)"

    $recordsJSON = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Params.records))
    $records = ($recordsJSON | ConvertFrom-Json)

    # records の完全なJSONを出力します
    Write-Output "Full Records JSON: $recordsJSON"

    # records からプロバイダーのタイトルを取得します
    $title = ($records | Where-Object {$_.uid -eq $Params.providerRecordUid}).title
    Write-Output "Provider Title=$title"

    # すべてのレコードをループし、詳細を表示します
    foreach ($record in $records) {
        Write-Output "Record UID=$($record.uid)"
        Write-Output "Record Title=$($record.title)"
        Write-Output "Record Type=$($record.type)"
        Write-Output "Record Details=$($record.details | ConvertTo-Json)"
    }
}

End {
    # パイプライン内の最後の項目が処理された後に一度だけ実行されます
}

```

以下は、Webhookをサードパーティのウェブサイトに送信するPowerShellスクリプトとなります。

```powershell
param (
    [Parameter(ValueFromPipeline=$true)]
    [string]
    $Record
)

# Base64形式の入力をデコードし、PowerShellオブジェクトに変換します
$RecordJsonAsB64 = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($Record))
$Params = $RecordJsonAsB64 | ConvertFrom-Json

# Webhookに送信するペイロードを準備します
$webhookPayload = @{
    providerRecordUid=$Params.providerRecordUid
    resourceRecordUid=$Params.resourceRecordUid
    userRecordUid=$Params.userRecordUid
    user=$Params.user
    timestamp= (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")
    message= "Post-rotation script executed successfully."
} | ConvertTo-Json

# WebhookのURLを定義します
$webhookUrl = "https://webhook.site/3308ec5a-3fba-4e31-85ad-37b0f643ac82"

# WebhookにPOSTリクエストを送信します
try {
    Invoke-RestMethod -Uri $webhookUrl -Method Post -Body $webhookPayload -ContentType 'application/json'
    Write-Host "Webhook message sent successfully."
}
catch {
    Write-Error "Failed to send webhook message: $_"
}
```

### KeeperシークレットマネージャーSDKの使用

ポストローテーションスクリプトはシェルスクリプトに限定されません。PythonやC#などの言語でアプリケーションを作成し、パイプされたパラメータを取得することもできます。ローテーションに関係するレコードUIDがパラメータとして渡されるため、ポストローテーションスクリプトでKeeperシークレットマネージャーSDKを使用して追加情報を取得できます。

```python
#!/usr/bin/env python3

import sys
import base64
import json

from keeper_secrets_manager_core import SecretsManager

# sys.stdin は配列ではないため、添字でアクセスできません(例：sys.stdin[0] は不可)
for base64_params in sys.stdin:
    params = json.loads(base64.b64decode(base64_params).decode())
        
    print(f"providerRecordUid={params.get('providerRecordUid')}")
    print(f"resourceRecordUid={params.get('resourceRecordUid')}")
    print(f"userRecordUid={params.get('userRecordUid')}")
    print(f"newPassword={params.get('newPassword')}")
    print(f"oldPassword={params.get('oldPassword')}")
    print(f"user={params.get('user')}")

    records = json.loads(base64.b64decode(params.get('records')).decode())
    print("Provider Title="
        f"{next((x for x in records if x['uid'] == params.get('providerRecordUid')), None).get('title')}")

    ksm = SecretsManager(config=...)
    resource_records = ksm.get_secrets(params.get('userRecordUid'))[0]
    
    break
```


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.keeper.io/keeperpam/jp/privileged-access-manager/password-rotation/post-rotation-scripts/code-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
