Problem
Given a Java application that runs in an EC2 instance, we want to enable it to call AWS services. This is useful for example to call services like Secrets Manager to retrieve secrets.
Authentication with AWS services when running locally
When running locally, the SDK has several ways of obtaining the credentials. We will describe two of these alternatives.
Specifying credentials via the credentials file
This is the recommended approach. This option involves setting the credentials in the AWS credentials profile file on your local system, located at:
~/.aws/credentialson Linux, macOS, or UnixC:\Users\USERNAME\.aws\credentialson Windows
This file should contain lines in the following format:
[default]
aws_access_key_id = your_access_key_id
aws_secret_access_key = your_secret_access_key
Substitute your own AWS credentials values for the values your_access_key_id and your_secret_access_key.
Specifying credentials via environment variables
This option involves setting the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables:
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
Authentication when running inside an EC2 instance
When the application runs in an EC2 instance, the AWS SDK authenticates via the instances’ role. For each service you want to use, you’ll need to attach a policy (i.e. a rule) to the role. For example, to use AWS Secrets Manager, you need to add the policy SecretsManagerReadWrite to the instance’s role.
Adding the Java SDK to the project
You can either add the specific modules you are going to use (recommended approach) or you can add the entire AWS Java SDK as a dependency.
To add a specific module, check the exact name and latest version of the module you are looking for in https://mvnrepository.com/artifact/com.amazonaws. For example, for AWS Secrets Manager, the dependency to add, at the time of writing is:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-secretsmanager</artifactId>
<version>1.11.339</version>
</dependency>
To add the entire AWS SDK to your project, check the latest version in https://mvnrepository.com/artifact/com.amazonaws. At the time of writing, the dependency to add is:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.327</version>
</dependency>
</dependencies>
Sources
- About the AWS Java SDK:
- About setting up the credentials for AWS access: