0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonとAWS secrets managerを連携

Last updated at Posted at 2025-10-02

はじめに

今回は作業のイメージを確認したかっただけで、実際に試してません。手順はAIに聞いただけです。PC上のpythonとAWS secrets managerを連携します

前提

AWSCLIは利用可能であること

AWS 側の準備

✅ シークレットを作成

AWS マネジメントコンソール → Secrets Manager

[シークレットの保存] をクリック

「その他のシークレット」を選択し、以下のようなJSONを保存する:

{
  "username": "admin",
  "password": "Pa$$w0rd"
}

シークレット名を入力(例):

myapp/db-credentials

IAMユーザーの権限

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetSecretValue"
      ],
      "Resource": "*"
    }
  ]
}

これを使用するIAMユーザにアタッチする必要がある

python準備

pip install boto3
get_secret.py
import boto3
import json
from botocore.exceptions import ClientError

def get_secret(secret_name: str, region_name: str = "ap-northeast-1") -> dict:
    """
    AWS Secrets Manager からシークレットを取得する関数
    """
    # boto3 セッションを作成(~/.aws/credentials の認証情報を使用)
    session = boto3.session.Session()
    client = session.client(service_name="secretsmanager", region_name=region_name)

    try:
        # Secrets Managerから値を取得
        response = client.get_secret_value(SecretId=secret_name)

        # 文字列形式で保存されている場合
        if "SecretString" in response:
            return json.loads(response["SecretString"])
        else:
            # バイナリ形式の場合(ほぼレア)
            return {"binary": response["SecretBinary"].decode("utf-8")}

    except ClientError as e:
        print(f"[ERROR] Secrets Managerから取得できませんでした: {e}")
        raise e

if __name__ == "__main__":
    # 取得したいシークレット名を指定
    secret_name = "myapp/db-credentials"

    secret = get_secret(secret_name)

    print("取得したシークレット:", secret)
    print("username:", secret.get("username"))
    print("password:", secret.get("password"))

実行

python get_secret.py

まとめ

ローカルPCから実行する場合は AWS CLIの認証情報 が必要

boto3 は自動的に ~/.aws/credentials を読み込むので、追加設定は不要

client.get_secret_value(SecretId=...) で取得可能

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?