> 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/privileged-access-manager/password-rotation/rotation-use-cases/saas-account/snowflake-user.md).

# Snowflakeユーザー

![](/files/J8L7W7R7oZdfT9zKmC59)

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

本ページでは、Snowflake ConnectorとKeeperゲートウェイのポストローテーションスクリプトを使用して、Snowflakeユーザーのパスワードをローテーションする手順を取り扱います。

組み込みのSaaSローテーションを利用する場合は、[SaaSプラグイン](/keeperpam/jp/privileged-access-manager/password-rotation/rotation-use-cases/saas-plugins.md)をご参照ください。

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

以下がすでに完了していることを前提としています。

* Keeperシークレットマネージャー[アプリケーション](/keeperpam/jp/privileged-access-manager/getting-started/applications.md)が作成済みであること
* 関連レコードを格納する共有フォルダが作成されていること
* PAM構成が設定済みで、ゲートウェイが稼働中であること
* Python環境に `snowflake-connector-python` がインストールされていること

### Snowflakeコネクタのインストール <a href="#install-snowflake-connector" id="install-snowflake-connector"></a>

Snowflake Connector for Pythonは、PythonアプリケーションがSnowflakeに接続して標準操作を実行するためのインターフェースです。`keeper-gateway` 環境で仮想環境を有効にし、以下を実行します。

```
pip install snowflake-connector-python
```

仮想環境を使用する場合は、[Python実行環境の準備](/keeperpam/jp/privileged-access-manager/password-rotation/rotation-use-cases/saas-account/rotate-credential-via-rest-api.md#5-python-environment-setup)に従い、スクリプト先頭にシバン行を追加します。

## 1. Snowflake認証レコードの作成 <a href="#id-1-create-the-snowflake-authentication-record" id="id-1-create-the-snowflake-authentication-record"></a>

Snowflake管理者の認証情報を保存するPAMユーザーレコードを作成します。レコードタイトルは `Snowflake Authentication Record` とします。

* **ログイン**に管理者ユーザー名を設定
* **パスワード**に管理者パスワードを設定
* カスタムフィールド `snowflake_account_name` にSnowflakeアカウント名を設定

## 2. ローテーション対象ユーザーのPAMユーザーレコード作成 <a href="#id-2-set-up-rotation-record" id="id-2-set-up-rotation-record"></a>

ローテーション対象のSnowflakeユーザー用に2つ目のPAMユーザーレコードを作成します。

* **ログイン**にSnowflakeユーザー名を設定
* **パスワード**に現在のパスワードを設定 (空欄でも可)

## 3. ローテーション設定の構成 <a href="#id-3-configure-rotation-settings" id="id-3-configure-rotation-settings"></a>

**\[ローテーション設定]** で **\[セットアップ]** を開き、以下を設定します。

* **\[ローテーションプロファイル]:** **\[PAMスクリプトのみを実行する]**
* **\[ローテーションタイプ]:** 本例では**オンデマンド**
* **\[PAMリソース]:** ゲートウェイに対応するPAM構成
* **\[管理者認証情報レコード]:** 空欄のまま
* **\[アップデート]** で保存

## 4. ポストローテーションスクリプトのアップロード <a href="#id-4-upload-the-post-rotation-script" id="id-4-upload-the-post-rotation-script"></a>

**\[PAMスクリプト]** で **\[PAMスクリプトを追加]** をクリックし、以下のスクリプトを添付します。

* **\[ローテーションクレデンシャル]** に、手順1の `Snowflake Authentication Record` を指定

## Pythonスクリプト <a href="#python-script" id="python-script"></a>

以下は、Snowflakeユーザーの認証情報をローテーションするPAMスクリプトです。

{% code overflow="wrap" %}

```python
#!/usr/local/bin/pam_rotation_venv_python3

'''
Snowflakeユーザーアカウント用パスワードローテーションスクリプト

このスクリプトでは、指定されたSnowflakeユーザーのパスワードを
Snowflake Connectorパッケージを使用してローテーションします。
これにより、Snowflake環境内でユーザーパスワードの自動更新が可能になります。

注: Pythonインタープリタへのパスにスペースが含まれている場合、スクリプトの実行が失敗します。
これはLinuxのシバン行における既知の制限であり、
スペースを含まないパスにPythonインタープリタへのシンボリックリンクを作成する必要があります。
    例: sudo ln -s "/usr/local/bin/my python3.7" /usr/local/bin/pam_rotation_venv_python3
'''
import asyncio
import json
import sys
import base64

'''
デバッグのためにインストールされているパッケージを表示するオプションです。必要に応じてコメントを外して使用してください。
print("# \n# Installed packages for debugging:")
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages])
for m in installed_packages_list:
    print(f"  {m}")
'''

# snowflakeコネクタパッケージをインポート
try:
    import snowflake.connector
except ImportError:
    print("# Error: The 'snowflake connector' package could not be imported. Run 'pip install snowflake-connector-python' to install it.")
    exit(1)

def rotate(snowflake_account_name, snowflake_admin_user, snowflake_admin_pass, snowflake_user_name, new_password):
    """
    Connects with Snowflake using the snowflake.connector module.
    Rotate the password for a given Snowflake user.

    Args:
    - snowflake_account_name (str): The name of the Snowflake account to connect to.
    - snowflake_admin_user (str): The username of the Snowflake admin account.
    - snowflake_admin_pass (str): The password of the Snowflake admin account.
    - snowflake_user_name (str): The name of the Snowflake user whose password needs to be rotated.
    - new_password (str): The new password to be set for the Snowflake user.

    Returns:
    - None
    """

    # snowflake.connectorモジュールを使用して、Snowflakeアカウントに接続します。
    try:
        conn = snowflake.connector.connect(
        user=snowflake_admin_user,
        password=snowflake_admin_pass,
        account=snowflake_account_name
        )
    except Exception as E:
        print(f"Unable to connect to snowflake account. Error: {E}")
        exit(1)
    
    # カーソルオブジェクトを作成
    cur = conn.cursor()
    
    # 新しいユーザーのパスワードを変更
    try:
        change_pass_query = f"ALTER USER {snowflake_user_name} SET PASSWORD = '{new_password}'"
        cur.execute(change_pass_query)
    except Exception as E:
        print(f"Unable to update the password. Error: {E}")
        exit(1)

    # カーソルと接続を閉じる
    cur.close()
    conn.close()

    print(f"Password successfully rotated for the given Snowflake User - {snowflake_user_name}")

def main():
    """
    Main function to rotate the password for a given Snowflake User.

    Reads and decodes input parameters from stdin, including the authentication record details
    and the new password. Then, updates the password of the specified Snowflake user.

    Args:
    - None

    Returns:
    - None
    """
    record_title = 'Snowflake Authentication Record' #これは、管理者認証情報を含むレコードのタイトルと同じである必要があります。
    admin_credential_record = None
    params = None
    
    # 標準入力からパラメータを読み取り、デコードする
    for base64_params in sys.stdin:
        params = json.loads(base64.b64decode(base64_params).decode())
        '''
        # Optionally print available params for debugging. Uncomment if needed.
        # print(f"# \n# Available params for the script:")
        # for key, value in params.items():
        #     print(f"#     {key}={value}")
        '''

        records = json.loads(base64.b64decode(params.get('records')).decode()) # PAMスクリプトセクションで「Rotation Credential」レコードとしてJSON文字列で渡されたレコードをデコードしてロードする

        # タイトルを使って、管理者アカウントの詳細を含むレコードを見つける
        admin_credential_record = next((record for record in records if record['title'].lower() == record_title.lower()), None)
        break

    if admin_credential_record is None:
        print(f"# Error: No Record with the access token found. Title: {record_title}")
        exit(1)

    # レコードから詳細を抽出する
    snowflake_account_name = admin_credential_record.get('snowflake_account_name')
    snowflake_admin_user = admin_credential_record.get('login')
    snowflake_admin_pass = admin_credential_record.get('password')
    
    # パスワードをローテーションする必要があるユーザーのユーザー名
    snowflake_user_name = params.get('user')

    # 新しくローテーションされたパスワードを抽出
    new_password = params.get('newPassword')
    
    if not all([snowflake_account_name, snowflake_admin_user, snowflake_admin_pass]):
        print("# Error: One or more required fields are missing in the authentication record.")
        exit(1)
   
    # 指定されたSnowflakeユーザーのパスワードをローテーションする
    rotate(snowflake_account_name, snowflake_admin_user, snowflake_admin_pass, snowflake_user_name, new_password)

if __name__ == "__main__":
    main()
```

{% endcode %}

GitHubでも入手できます。

{% embed url="<https://github.com/Keeper-Security/Zero-Trust-KeeperPAM-Scripts/blob/main/snowflake/update_snowflake_user.py>" %}

## 5. Python実行環境の準備 <a href="#id-5-python-environment-setup" id="id-5-python-environment-setup"></a>

**\[追加認証情報]** で手順1のSnowflake認証レコードを選択し、**\[コマンドプレフィックス付きで実行]** を有効にしてPython実行ファイルのフルパスを指定します。Docker経由のゲートウェイでは通常 `/usr/local/bin/python3` です。

## 6. 構成の保存とローテーションの実行 <a href="#id-6-save-and-run-rotation" id="id-6-save-and-run-rotation"></a>

PAMユーザーレコードで **\[保存]** をクリックします。設定後、**\[PAMスクリプトのみを実行]** でオンデマンドローテーションを実行できます。

!\[]\(../../../../.gitbook/assets/snowflake record.png)


---

# 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 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/rotation-use-cases/saas-account/snowflake-user.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.
