Integrate AWS Secrets Manager in Spring Boot
Introduction
Hardcoding credentials — even in application.yml behind environment-variable placeholders — is a known risk. Your secrets end up in GitHub history, CI logs, or debug dumps. AWS Secrets Manager gives you encrypted-at-rest, rotation-aware secret storage with fine-grained access control and automatic distribution to databases, APIs, and third-party tools.
This guide walks through integrating AWS Secrets Manager into a Spring Boot application: wiring the SDK v2, bootstrapping secrets into Environment properties, achieving dynamic refresh on rotation, and hardening for ECS/EKS/local dev.
Why AWS Secrets Manager Over Alternatives?
| Approach | Weakness | Secrets Manager Strength |
|---|---|---|
| Plain env vars | Visible in process tables, container inspectors, CI logs | Encrypted at rest (KMS); never printed by the platform |
| Git-encrypted (SOPS) | Key management fallback; revocation hard | Central rotation, IAM-scoped retrieval, audit via CloudTrail |
| SSM Parameter Store (SecureString) | No managed rotation for non-RDS resources; region-bound only | Native rotation Lambdas, cross-account sharing, replica regions |
Prerequisites
- Spring Boot 3.x project (Java 17+)
- AWS account — one or more secrets created in Secrets Manager
- IAM credentials available via one of: local AWS CLI profile, ECS task role, EKS IRSA/Amazon issuer, or EC2 instance profile
aws-clito create and inspect secrets while testing
Step 1: Define the Secret in AWS
Store JSON secrets — Secrets Manager supports plaintext and key/value JSON:
aws secretsmanager create-secret \
--name prod/api/db-credentials \
--description "Spring Boot production database" \
--secret-string '{"username":"orders_app","password":"Correct-Horse-Battery2!"}'
Record the returned ARN: arn:aws:secretsmanager:us-east-1:111122223333:secret:prod/api/db-credentials-AbCdEf
Step 2: Add Dependencies
Spring Cloud AWS bundles the AWS SDK v2 and auto-detects IAM-based credentials:
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-starter-secrets-manager</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Optional: observability -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Step 3: IAM Permissions
Give the application identity just enough access:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadSecretsForThisApp",
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue",
"secretsmanager:DescribeSecret"
],
"Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:prod/api/db-credentials-*"
}
]
}
Least privilege: scope to the specific secret ARNs the service consumes, never * unless in a sandbox.
Step 4: Two Integration Patterns
Pattern A — Implicit PropertySource (zero boilerplate):
Spring Cloud AWS Secrets Manager can expose an ARN as property values automatically when the property name matches the secret name. Enable with a tiny property:
# application.yml
spring:
cloud:
aws:
secretsmanager:
enabled: true
prefix: aws- # property keys look up secrets
datasource:
url: jdbc:postgresql://${aws.prod.api.db-credentials.host}:5432/orders
username: ${aws.prod.api.db-credentials.username}
password: ${aws.prod.api.db-credentials.password}
This flattens JSON keys into Spring properties - convenient for simple secrets.
Pattern B — Programmatic client (full control, recommended for advanced use):
Use the injected SecretsManagerClient to read JSON and hydrate typed configuration:
@Configuration
@ConfigurationProperties(prefix = "app.secrets.db")
public class DatabaseSecretProperties {
private String username;
private String password;
private String host;
private String port;
private int maxPoolSize = 10;
// getters/setters, validation annotations...
}
@Configuration
public class SecretsWiringConfig {
private final SecretsManagerClient secretsManager;
public SecretsWiringConfig(SecretsManagerClient secretsManager) {
this.secretsManager = secretsManager;
}
@Bean
@ConfigurationPropertiesBinding
public DatabaseSecretProperties dbSecrets(
@Value("${app.secrets.db.arn}") String arn) {
String json = secretsManager.getSecretValue(
GetSecretValueRequest.builder().secretId(arn).build())
.secretString();
DatabaseSecretProperties props = new DatabaseSecretProperties();
JsonUtils.mapToObject(json, props); // e.g. Jackson ObjectMapper.convertValue
return props;
}
}
Step 5: Dynamic Refresh on Rotation
AWS Secrets Manager can rotate a secret (e.g., every 30 days for RDS). Static client-side config would serve stale credentials. The robust approach: poll DescribeSecret for VersionChanged or use the Secrets Manager rotation client in the SDK, then re-read into a versioned holder:
@Service
public class RotatingDbSecretService implements ApplicationRunner {
private final SecretsManagerClient sm;
private final MeterRegistry metrics;
private volatile DatabaseSecretProperties snapshot;
@Scheduled(fixedDelay = 60_000, initialDelay = 10_000)
public void refreshIfRotated() {
DescribeSecretResponse desc = sm.describeSecret(
DescribeSecretRequest.builder().secretId(arn).build());
String currentVersion = desc.versionIdsToStages().values().stream()
.findFirst().orElse("");
if (!currentVersion.equals(lastVersion)) {
snapshot = loadFromSm(arn);
lastVersion = currentVersion;
metrics.counter("secrets.refresh.count").increment();
}
}
For real connection hand-off (closing & reopening pools), implement SmartLifecycle or recreate the HikariDataSource bean and publish a Spring application event that repository/transaction consumers handle gracefully.
Step 6: Security and Operational Hardening
| Area | Recommendation |
|---|---|
| Encryption | Enable automatic rotation; rotate with a dedicated Lambda; verify LastRotatedDate via CloudWatch alarm. |
| Audit | CloudTrail logs every GetSecretValue; alert on Decrypt from unexpected roles. |
| Network | Attach resource policy to secret; allow only the app role and the rotation Lambda principal. |
| Local development | Use ~/.aws/credentials or AWS_PROFILE; keep a local Spring profile with dummy values; never commit real ARNs. |
| Failsafe | Default pool connectionTimeout < 2s so a Secrets Manager outage fails fast instead of hanging startup. |
Step 7: Testing Strategies
- Unit tests: mock
SecretsManagerClientat the boundary; test the mapping and parsing logic only. - Integration tests: use LocalStack or a dedicated "test" secret in a lower environment; assert the wiring bean resolves values.
- Local-only secret: in
application-local.ymlsetapp.secrets.db.arnto a dummy and runAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEYenv vars pointing to LocalStack.
# application-test.yml
spring:
cloud:
aws:
region:
static: us-east-1
credentials:
instance-profile: false
secretsmanager:
enabled: false # prevent real AWS calls entirely in unit tests
app:
secrets:
db:
username: test_user
password: test_pass
Troubleshooting Common Issues
| Symptom | Cause / Fix |
|---|---|
AccessDeniedException on startup |
App IAM role lacks secretsmanager:GetSecretValue; check residual policy on the secret; confirm Resource ARN matches exactly. |
| Blank password from Pattern A | Property prefix mismatch; verify secret is JSON and key mapping matches (e.g., username vs user). |
| Timeout connecting to Secrets Manager | VPC endpoint com.amazonaws.region.secretsmanager not attached; add interface endpoint + SG rules for HTTPS. |
| Stale credentials after rotation | No refresh loop wired (Pattern B); add scheduled/refresh mechanism above and let pools cycle. |
Regional endpoints disabled |
SDK v2 with default provider chain; set aws.region explicitly on the client builder or in Boot config. |
Wrap-up
Whether you adopt the low-touch property binding of Spring Cloud AWS (Pattern A) or the fully controlled SDK + rotation loop (Pattern B), the core outcome is identical: credentials live in one encrypted, auditable, IAM-scoped system — and your Spring source code stays free of secrets. Combined with the DocumentDB and ElastiCache patterns from our series, this gives you a fully managed, secrets-safe data layer.
Comments
Post a Comment