LoginSignup
1
0

AWS Secrets Managerを使ってみた

Posted at

AWS Secrets Managerとは?

データベース認証情報、アプリケーション認証情報、OAuth トークン、API キー、およびその他のシークレットをライフサイクルを通じて管理、取得、ローテーションするのに役立ちます。多くの AWS サービスは、Secrets Manager でシークレットを保存して使用します
https://docs.aws.amazon.com/ja_jp/secretsmanager/latest/userguide/intro.html

ソースコードにパスワードを記載する必要がなくなるので、セキュリティ的にもよく、
ローテーション機能があり定期的にパスワードを更新することができます

AWS Secrets Managerの設定

  1. AWS Secrets Managerのページを開き、新しいシークレットを保存するを選択

  2. シークレットのタイプを選択
    今回はその他のシークレットのタイプにしたので、保存する値も設定します
    image.png

  3. シークレットの名前を設定
    APIで取得する際に使用する名前を設定します
    またリージョンで障害が起きた時用に他のリージョンに読み取り専用のデータを保存することもできるようです
    image-1.png

  4. ローテーションの設定
    自動的にローテーションを行いたい場合は設定を行います
    image-2.png

シークレット取得

Secrets Managerの設定時にpythonのサンプルコードがありました
ローカルで取得するために多少変更を加えて実行し、設定した値が取得できました

コード

# Use this code snippet in your app.
# If you need more information about configurations
# or implementing the sample code, visit the AWS docs:
# https://aws.amazon.com/developer/language/python/

import boto3
from botocore.exceptions import ClientError


def get_secret():

    secret_name = "" # 3.で設定したシークレットの名前
    region_name = "" # Secrets Managerを作成したリージョン

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        aws_access_key_id = '', # アクセスキー
        aws_secret_access_key  = '', # シークレットキー
        service_name='secretsmanager',
        region_name=region_name
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        # For a list of exceptions thrown, see
        # https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
        raise e

    secret = get_secret_value_response['SecretString']

    # Your code goes here.

    return secret

print(get_secret())

結果

{"test1":"example","test2":"default"}
1
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
1
0