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?

DjangoのSECRET_KEYをAWS Secrets Managerで安全に管理する方法

Posted at

手順1:Secrets Managerの作成

シークレットのタイプを選択

設定項目 入力内容
シークレットのタイプ その他のシークレットのタイプ
キー SECRET_KEY
パスワード パスワード入力
暗号化キー aws/secretsmanager

入力が完了しましたら、次へをクリックします

シークレットを設定

設定項目 入力内容
シークレットの名前 sample/demo/secret_key

入力が完了しましたら、次へをクリックします

ローテーションを設定する

  1. 自動ローテーションは設定しない
  2. 入力が完了しましたら、次へをクリックします

レビュー

変更がなければ、保存をクリックします

手順2:DjangoでSecrets Managerのシークレットを読み込む設定

settings.py
import boto3
from botocore.exceptions import ClientError
import json

def get_secret_key():

    secret_name = "sample/demo/secret_key"
    region_name = "ap-northeast-1"

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        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']
    return json.loads(secret)


secret_keys = get_secret_key()

SECRET_KEY = secret_keys["SECRET_KEY"]

おまけ:EC2インスタンスにIAMロールをアタッチ

EC2を作成済みという前提で進みます

手順1:IAMロールの作成

IAMのロールのロールを作成をクリック

信頼されたエンティティを選択

設定項目 入力内容
信頼されたエンティティタイプ AWSのサービス
サービスまたはユースケース EC2
ユースケース EC2

入力が完了しましたら、次へをクリックします

許可を追加

設定項目 入力内容
許可ポリシー SecretsManagerReadWrite

入力が完了しましたら、次へをクリックします

名前、確認、および作成

設定項目 入力内容
ロール名 sample-ec2-role
説明 Allows EC2 instances to call AWS services on your behalf.

入力が完了しましたら、ロールを作成をクリックします

手順2:EC2のIAMロールを変更

EC2管理画面 → インスタンス選択 → 「アクション」→「セキュリティ」→「IAM ロールの変更」

設定項目 入力内容
IAMロール sample-ec2-role

入力が完了しましたら、IAM ロールの更新をクリックします

手順3:EC2インスタンス上で再実行

指定したシークレット名の情報を取得できるかを確認

aws secretsmanager get-secret-value --secret-id <シークレット名>

成功した場合は、SecretStringなどが表示されます

まとめ

AWS Secrets Managerに保存したSECRET_KEYを、Djangoアプリケーションのsettings.pyでboto3を用いて安全に取得する設定方法を解説しました。

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?