To store a username and password in AWS Secret Manager and fetch it using a Lambda function, follow these steps:
- Create a secret in AWS Secret Manager
- Create a Lambda function with a REST API endpoint
- Deploy the Lambda function with the API endpoint
- Call the Lambda function from a script runner
Here is a detailed explanation with Java code for each step:
- Create a secret in AWS Secret Manager:
a. Go to the AWS Secret Manager console and click on "Create secret".
b. Enter a name for the secret, e.g., "MySecret".
c. Set the secret type to "String".
d. Enter the username and password in the secret value, separated by a delimiter (e.g., a comma or a new line).
- Create a Lambda function with a REST API endpoint:
a. Go to the AWS Lambda console and click on "Create function".
b. Choose "Author from scratch".
c. Enter a function name, e.g., "MySecretFetcher".
d. Choose a runtime, e.g., Java 8.
e. Click on "Create function".
f. In the Lambda function code editor, paste the following Java code:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult;
import java.io.IOException;
import java.util.Map;
public class SecretFetcher implements RequestHandler<Map<String, String>, String> {
public String handleRequest(Map<String, String> input, Context context) {
String secretName = input.get("secretName");
AWSSecretsManager client = AWSSecretsManagerClientBuilder.defaultClient();
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
.withSecretId(secret