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?

Spring BootアプリケーションでAWS Secrets Managerから機密情報(DB認証情報など)を安全に取得する方法

Last updated at Posted at 2025-03-31

Spring Boot × AWS Secrets Manager:セキュアな設定管理の実践ガイド

はじめに

アプリケーションの設定情報(例:データベース接続情報)をプロパティファイルや環境変数に直接記載することは、セキュリティリスクを伴います。

本記事では、Spring Bootアプリケーションから AWS Secrets Manager を利用して、安全にデータベースなどの機密情報を取得し、システムプロパティに反映させる方法を解説します。

使用技術・ライブラリ

Spring Boot 3.3.4
Java 21
AWS SDK v1 (Secrets Manager)
AWS X-Ray(オプション、トレース用)

プロジェクト構成とポイント

Demo10Application.java でアプリケーション起動前に AWS Secrets Manager から秘密情報を取得し、Spring Bootに必要な設定情報(例:spring.datasource.url)を動的に設定します。

Secrets Managerに登録する値の例(JSON形式):

{
  "DB_ENDPOINT": "your-db.cluster-xyz.ap-northeast-1.rds.amazonaws.com:5432",
  "DB_USERNAME": "postgres",
  "DB_PASSWORD": "yourpassword",
  "DB_PLATFORM": "postgresql",
  "DB_NAME": "yourdbname",
  "UPLOAD_DIRECTORY": "/data/uploads",
  "SECRET_KEY": "supersecretkey123"
}

処理フローの解説

  1. main()内でSecretsの読み込みをトリガー
public static void main(String[] args) {
    boolean configLoaded = loadConfiguration();
    if (!configLoaded) {
        log.severe("設定の読み込みに失敗しました。アプリケーションを終了します。");
        System.exit(1);
    }
    SpringApplication.run(Demo10Application.class, args);
}

起動前に設定取得が失敗した場合は、安全のためアプリケーションを終了します。

  1. Secrets Managerから取得する処理
AWSSecretsManager client = AWSSecretsManagerClientBuilder.standard()
    .withRegion(region)
    .build();

GetSecretValueRequest postgresRequest = new GetSecretValueRequest()
    .withSecretId(postgresSecretArn);

GetSecretValueResult postgresResult = client.getSecretValue(postgresRequest);
リージョンは ap-northeast-1(東京リージョン)で設定。
  1. SecretsのJSONを解析し、必要なプロパティを設定
JsonNode postgresSecretJson = objectMapper.readTree(result.getSecretString());
System.setProperty("DB_ENDPOINT", postgresSecretJson.get("DB_ENDPOINT").asText());
System.setProperty("spring.datasource.url", "jdbc:postgresql://" + dbEndpoint + "/" + dbName);
ここでSpring Bootが使用する spring.datasource.url なども動的に設定。

設定ファイル(build.gradle)に必要な依存関係

implementation 'com.amazonaws:aws-java-sdk-secretsmanager:1.12.465'
implementation 'com.amazonaws:aws-xray-recorder-sdk-spring:2.15.0'
implementation 'org.postgresql:postgresql'
Secrets Manager SDKとX-Ray(任意)を含めましょう。

実行時の注意点

IAMロールが secretsmanager:GetSecretValue 権限を持っていること

AWS_REGION 環境変数 or System.setProperty("aws.region", "ap-northeast-1") の設定が必要

ローカル実行時は ~/.aws/credentials に適切なプロファイルが必要

まとめ

AWS Secrets Managerを利用することで、機密情報のハードコーディングを避け、セキュアでスケーラブルな構成管理が可能になります。

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?