How to specify aws profile in java client code

AWS SDK provides easy way to switch profiles for local development programmatically if you are using non-default profile for your application.

Problem

Problem may appear in different ways

  • Problem Connecting to DynamoDb: Unable to load AWS credentials from any provider in the chain OR
  • Unable to find Resource

Solution

If you are using default profile for your local environment, you can use below code.

DynamoDbConfig.java
AmazonDynamoDBClient client = new AmazonDynamoDBClient(
          new AWSCredentialsProviderChain(            
              // First we'll check for EC2 instance profile credentials - Will be executed in AWS environment
              new InstanceProfileCredentialsProvider(),     
          // If we're not on an EC2 instance, fall back to checking for
          // credentials in the local credentials profile file - Local Development environment.
          new ProfileCredentialsProvider()));

If you are using non default profile for your local environment, you can use below code.

In below code, development is the profile name. It means that in you ~/.aws/credentials, you should have development as configured profile with keys and credentials

AwsIdleConnectionShutdownBean.java
AmazonDynamoDBClient client = new AmazonDynamoDBClient(
          new AWSCredentialsProviderChain(            
              // First we'll check for EC2 instance profile credentials - Will be executed in AWS environment
              new InstanceProfileCredentialsProvider(),     
          // If we're not on an EC2 instance, fall back to checking for
          // credentials in the local credentials profile file - Local Development environment.
          new ProfileCredentialsProvider("development")));

Reference


Version History


Date Description
2016-11-17    Initial Version