aws-sdk-java-v2-secrets-manager ยท diff
git:20260223.c6d4db1 to git:20260323.2528036
93 added, 296 removed. Audit A to A.
---
name: aws-sdk-java-v2-secrets-manager
- description: Provides AWS Secrets Manager patterns using AWS SDK for Java 2.x. Use when storing/retrieving secrets (passwords, API keys, tokens), rotating secrets automatically, managing database credentials, or integrating secret management into Spring Boot applications.
+ description: Provides AWS Secrets Manager patterns for AWS SDK for Java 2.x, including secret retrieval, caching, rotation-aware access, and Spring Boot integration. Use when storing or reading secrets in Java services, replacing hardcoded credentials, or wiring secret-backed configuration into applications.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---
# AWS SDK for Java 2.x - AWS Secrets Manager
## Overview
- AWS Secrets Manager helps you protect secrets needed to access your applications, services, and IT resources. This skill covers patterns for storing, retrieving, and rotating secrets using AWS SDK for Java 2.x, including Spring Boot integration and caching strategies.
-
- ## When to Use
-
- Use this skill when:
- - Storing and retrieving application secrets programmatically
- - Managing database credentials securely without hardcoding
- - Implementing automatic secret rotation with Lambda functions
- - Integrating AWS Secrets Manager with Spring Boot applications
- - Setting up secret caching for improved performance
- - Creating secure configuration management systems
- - Working with multi-region secret deployments
- - Implementing audit logging for secret access
-
- ## Instructions
-
- Follow these steps to work with AWS Secrets Manager:
-
- 1. **Add Dependencies** - Include secretsmanager dependency and caching library
- 2. **Create Client** - Instantiate SecretsManagerClient with proper configuration
- 3. **Store Secrets** - Use createSecret() to store new secrets
- 4. **Retrieve Secrets** - Use getSecretValue() to fetch secrets
- 5. **Implement Caching** - Use SecretCache for improved performance
- 6. **Configure Rotation** - Set up automatic rotation schedules
- 7. **Integrate with Spring** - Configure beans and property sources
- 8. **Monitor Access** - Enable CloudTrail logging for audit trails
-
- ## Dependencies
+ Use this skill to manage application secrets with AWS Secrets Manager from Java services.
- ### Maven
- ```xml
- <dependency>
- <groupId>software.amazon.awssdk</groupId>
- <artifactId>secretsmanager</artifactId>
- </dependency>
+ It focuses on the operational flow that matters in production:
+ - how to retrieve and deserialize secrets safely
+ - when to add local caching
+ - how to integrate secret access into Spring Boot without leaking values into logs or configuration files
- <!-- For secret caching (recommended for production) -->
- <dependency>
- <groupId>com.amazonaws.secretsmanager</groupId>
- <artifactId>aws-secretsmanager-caching-java</artifactId>
- <version>2.0.0</version> // Use the sdk v2 compatible version
- </dependency>
- ```
+ Keep large API notes and extended setup details in the bundled references.
- ### Gradle
- ```gradle
- implementation 'software.amazon.awssdk:secretsmanager'
- implementation 'com.amazonaws.secretsmanager:aws-secretsmanager-caching-java:2.0.0
- ```
+ ## When to Use
- ## Quick Start
+ Use this skill when:
+ - replacing hardcoded passwords, API keys, or tokens with managed secrets
+ - loading database credentials or third-party API credentials at runtime
+ - adding caching to reduce Secrets Manager latency and API cost
+ - handling secret version stages such as `AWSCURRENT` and `AWSPENDING`
+ - wiring secret access into Spring Boot beans or configuration services
+ - preparing rotation-aware applications or Lambda rotation workflows
- ### Basic Client Setup
- ```java
- import software.amazon.awssdk.regions.Region;
- import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
+ Typical trigger phrases include `java secrets manager`, `spring boot secret`, `aws secret cache`, `load db credentials from secrets manager`, and `rotate secret`.
- SecretsManagerClient secretsClient = SecretsManagerClient.builder()
- .region(Region.US_EAST_1)
- .build();
- ```
+ ## Instructions
- ### Store a Secret
- ```java
- import software.amazon.awssdk.services.secretsmanager.model.*;
+ ### 1. Model the secret before writing access code
- public String createSecret(String secretName, String secretValue) {
- CreateSecretRequest request = CreateSecretRequest.builder()
- .name(secretName)
- .secretString(secretValue)
- .build();
+ Decide:
+ - the secret name and path convention
+ - whether the value is plain text or structured JSON
+ - which application boundary is allowed to read it
+ - whether the caller needs the latest value on every request or can tolerate a cache
- CreateSecretResponse response = secretsClient.createSecret(request);
- return response.arn();
- }
- ```
+ Prefer JSON secrets for multi-field credentials such as database connection details.
- ### Retrieve a Secret
- ```java
- public String getSecretValue(String secretName) {
- GetSecretValueRequest request = GetSecretValueRequest.builder()
- .secretId(secretName)
- .build();
+ ### 2. Create one reusable client per application configuration
- GetSecretValueResponse response = secretsClient.getSecretValue(request);
- return response.secretString();
- }
- ```
+ Use a single `SecretsManagerClient` with explicit region and the default credential provider chain unless the environment requires something more specific.
- ## Core Operations
+ Keep client creation in configuration code, not in business services.
- ### Secret Management
- - Create secrets with `createSecret()`
- - Retrieve secrets with `getSecretValue()`
- - Update secrets with `updateSecret()`
- - Delete secrets with `deleteSecret()`
- - List secrets with `listSecrets()`
- - Restore deleted secrets with `restoreSecret()`
+ ### 3. Retrieve and deserialize at the boundary layer
- ### Secret Versioning
- - Access specific versions by `versionId`
- - Access versions by stage (e.g., "AWSCURRENT", "AWSPENDING")
- - Automatically manage version history
+ At the integration boundary:
+ - fetch with `GetSecretValueRequest`
+ - deserialize JSON into a typed object or validated map
+ - convert AWS exceptions into application-level errors
+ - never log `secretString()` or include it in thrown exception messages
- ### Secret Rotation
- - Configure automatic rotation schedules
- - Lambda-based rotation functions
- - Immediate rotation with `rotateSecret()`
+ ### 4. Add caching only where it solves a real problem
- ## Caching for Performance
+ Use caching when:
+ - the secret is read frequently
+ - latency matters for startup or request handling
+ - the cost of repeated lookups is material
- ### Setup Cache
- ```java
- import com.amazonaws.secretsmanager.caching.SecretCache;
+ Document cache TTL expectations clearly, especially if the secret rotates.
- public class CachedSecrets {
- private final SecretCache cache;
+ ### 5. Design for rotation and staged versions
- public CachedSecrets(SecretsManagerClient secretsClient) {
- this.cache = new SecretCache(secretsClient);
- }
+ If the secret rotates:
+ - read through a thin service layer so cache invalidation and retry behavior stay centralized
+ - understand which callers must tolerate `AWSPENDING` during verification workflows
+ - test how the application behaves during stale cache windows or partial rotation failures
- public String getCachedSecret(String secretName) {
- return cache.getSecretString(secretName);
- }
- }
- ```
+ ### 6. Validate end-to-end behavior
- ### Cache Configuration
- ```java
- import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration;
+ Before shipping:
+ - verify IAM permissions and KMS access
+ - test missing secret, wrong region, and decryption failure paths
+ - confirm secrets are not surfaced in logs, metrics, or debug endpoints
+ - prove database or API clients refresh correctly when credentials rotate
- SecretCacheConfiguration config = SecretCacheConfiguration.builder()
- .maxCacheSize(1000)
- .cacheItemTTL(3600000) // 1 hour
- .build();
- ```
+ ## Examples
- ## Spring Boot Integration
+ ### Example 1: Reusable client and typed secret lookup
- ### Configuration
```java
@Configuration
- public class SecretsManagerConfiguration {
+ public class SecretsConfiguration {
@Bean
- public SecretsManagerClient secretsManagerClient() {
+ SecretsManagerClient secretsManagerClient() {
return SecretsManagerClient.builder()
- .region(Region.of(region))
+ .region(Region.of("eu-south-2"))
+ .credentialsProvider(DefaultCredentialsProvider.create())
.build();
}
-
- @Bean
- public SecretCache secretCache(SecretsManagerClient secretsClient) {
- return new SecretCache(secretsClient);
- }
}
- ```
- ### Service Layer
- ```java
@Service
public class SecretsService {
- private final SecretCache cache;
-
- public SecretsService(SecretCache cache) {
- this.cache = cache;
- }
-
- public <T> T getSecretAsObject(String secretName, Class<T> type) {
- String secretJson = cache.getSecretString(secretName);
- return objectMapper.readValue(secretJson, type);
- }
- }
- ```
-
- ### Database Configuration
- ```java
- @Configuration
- public class DatabaseConfiguration {
-
- @Bean
- public DataSource dataSource(SecretsService secretsService) {
- Map<String, String> credentials = secretsService.getSecretAsMap(
- "prod/database/credentials");
-
- HikariConfig config = new HikariConfig();
- config.setJdbcUrl(credentials.get("url"));
- config.setUsername(credentials.get("username"));
- config.setPassword(credentials.get("password"));
+ private final SecretsManagerClient client;
+ private final ObjectMapper objectMapper;
- return new HikariDataSource(config);
+ public SecretsService(SecretsManagerClient client, ObjectMapper objectMapper) {
+ this.client = client;
+ this.objectMapper = objectMapper;
}
- }
- ```
- ## Examples
-
- ### Database Credentials Structure
- ```json
- {
- "engine": "postgres",
- "host": "mydb.us-east-1.rds.amazonaws.com",
- "port": 5432,
- "username": "admin",
- "password": "MySecurePassword123!",
- "dbname": "mydatabase",
- "url": "jdbc:postgresql://mydb.us-east-1.rds.amazonaws.com:5432/mydatabase"
- }
- ```
-
- ### API Keys Structure
- ```json
- {
- "api_key": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
- "api_secret": "MySecretKey123!",
- "api_token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
- }
- ```
-
- ## Common Patterns
-
- ### Error Handling
- ```java
- try {
- String secret = secretsClient.getSecretValue(request).secretString();
- } catch (SecretsManagerException e) {
- if (e.awsErrorDetails().errorCode().equals("ResourceNotFoundException")) {
- // Handle missing secret
+ public DatabaseSecret loadDatabaseSecret(String secretId) throws JsonProcessingException {
+ GetSecretValueResponse response = client.getSecretValue(
+ GetSecretValueRequest.builder().secretId(secretId).build()
+ );
+ return objectMapper.readValue(response.secretString(), DatabaseSecret.class);
}
- throw e;
}
```
- ### Batch Operations
- ```java
- List<String> secretNames = List.of("secret1", "secret2", "secret3");
- Map<String, String> secrets = secretNames.stream()
- .collect(Collectors.toMap(
- Function.identity(),
- name -> cache.getSecretString(name)
- ));
- ```
-
- ## Best Practices
-
- 1. **Secret Management**:
- - Use descriptive secret names with hierarchical structure
- - Implement versioning and rotation
- - Add tags for organization and billing
-
- 2. **Caching**:
- - Always use caching in production environments
- - Configure appropriate TTL values based on secret sensitivity
- - Monitor cache hit rates
-
- 3. **Security**:
- - Never log secret values
- - Use KMS encryption for sensitive secrets
- - Implement least privilege IAM policies
- - Enable CloudTrail logging
-
- 4. **Performance**:
- - Reuse SecretsManagerClient instances
- - Use async operations when appropriate
- - Monitor API throttling limits
-
- 5. **Spring Boot Integration**:
- - Use `@Value` annotations for secret names
- - Implement proper exception handling
- - Use configuration properties for secret names
-
- ## Testing Strategies
+ ### Example 2: Cache a hot-path secret lookup
- ### Unit Testing
```java
- @ExtendWith(MockitoExtension.class)
- class SecretsServiceTest {
-
- @Mock
- private SecretCache cache;
-
- @InjectMocks
- private SecretsService secretsService;
-
- @Test
- void shouldGetSecret() {
- when(cache.getSecretString("test-secret")).thenReturn("secret-value");
+ public class CachedSecretsService {
- String result = secretsService.getSecret("test-secret");
+ private final SecretCache cache;
- assertEquals("secret-value", result);
+ public CachedSecretsService(SecretsManagerClient client) {
+ this.cache = new SecretCache(client);
}
- }
- ```
- ### Integration Testing
- ```java
- @SpringBootTest(classes = TestSecretsConfiguration.class)
- class SecretsManagerIntegrationTest {
-
- @Autowired
- private SecretsService secretsService;
-
- @Test
- void shouldRetrieveSecret() {
- String secret = secretsService.getSecret("test-secret");
- assertNotNull(secret);
+ public String apiToken(String secretId) {
+ return cache.getSecretString(secretId);
}
}
```
- ## Troubleshooting
+ Use this pattern only when the application can tolerate the chosen cache refresh behavior.
- ### Common Issues
- - **Access Denied**: Check IAM permissions
- - **Resource Not Found**: Verify secret name and region
- - **Decryption Failure**: Ensure KMS key permissions
- - **Throttling**: Implement retry logic and backoff
+ ## Best Practices
- ### Debug Commands
- ```bash
- # Check secret exists
- aws secretsmanager describe-secret --secret-id my-secret
+ - Use hierarchical secret names that match domain and environment boundaries.
+ - Prefer typed JSON deserialization over string parsing scattered across the codebase.
+ - Keep secret retrieval in infrastructure services rather than controllers or entities.
+ - Reuse the SDK client and cache instances.
+ - Combine least-privilege IAM with KMS permissions and CloudTrail visibility.
+ - Make rotation behavior explicit in code and operational docs.
- # List all secrets
- aws secretsmanager list-secrets
+ ## Constraints and Warnings
- # Get secret value (CLI)
- aws secretsmanager get-secret-value --secret-id my-secret
- ```
+ - Do not log secret values, serialized secret objects, or decrypted payload fragments.
+ - Cached values may remain stale during or after rotation depending on TTL and refresh behavior.
+ - Secret access can fail because of IAM policy, KMS policy, region mismatch, or deleted versions; handle these cases explicitly.
+ - Automatic rotation is not available for every secret shape or integration.
+ - Large or frequently changing secrets may not be good candidates for aggressive in-memory caching.
## References
- For detailed information and advanced patterns, see:
-
- - [API Reference](./references/api-reference.md) - Complete API documentation
- - [Caching Guide](./references/caching-guide.md) - Performance optimization strategies
- - [Spring Boot Integration](./references/spring-boot-integration.md) - Complete Spring integration patterns
+ - `references/api-reference.md`
+ - `references/caching-guide.md`
+ - `references/spring-boot-integration.md`
## Related Skills
- - `aws-sdk-java-v2-core` - Core AWS SDK patterns and best practices
- - `aws-sdk-java-v2-kms` - KMS encryption and key management
- - `spring-boot-dependency-injection` - Spring dependency injection patterns
-
- ## Constraints and Warnings
+ - `aws-sdk-java-v2-core`
+ - `aws-sdk-java-v2-kms`
+ - `spring-boot-dependency-injection`
- - **Secret Size**: Maximum secret size is 10KB
- - **API Costs**: Each API call incurs a cost; use caching to reduce calls
- - **Rotation Limits**: Some secret types cannot be rotated automatically
- - **Replication Limits**: Multi-region secrets have replication limits
- - **Version Limits**: Secrets retain up to 100 versions including pending versions
- - **Deletion Delay**: Secret deletion requires 7-30 day recovery window
- - **KMS Encryption**: Secrets are encrypted using AWS KMS; key management is important
- - **Cache Consistency**: Cached secrets may be stale during rotation
- - **IAM Permissions**: Secrets require specific IAM actions for access
- - **Logging**: Avoid logging secret values; use CloudTrail for audit trails