'Testing application locally that uses IAM Role

I have a Java application which does adds files in S3. This application is running in a EC2 instance.

We are using IAM role. So we have attached the required IAM role to this EC2 instance.

Everything works perfect there.

But we would like to test the application locally in my laptop as well. It's hard to upload the application everytime to EC2 whenever I need to test it.

How can we switch dynamically without changing the code, so that I can test it my laptop (with accesskey and secretKey) as well as use IAM role in EC2?



Solution 1:[1]

You can provide your own order for searching credentials by using: https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/AWSCredentialsProviderChain.html

So in your case, order would be:

  1. InstanceProfileCredentialsProvider or EC2ContainerCredentialsProviderWrapper
  2. AWSStaticCredentialsProvider or EnvironmentVariableCredentialsProvider.

Add all your providers to provider chain constructor, then pass it to AWS client.

Solution 2:[2]

If you are using docker like instances , then it would be easy if you set environment variables to docker run.

docker run --env-file=FILE

OR

docker run -it --rm -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_KEY

Ref: https://hub.docker.com/r/pmcjury/aws-cli/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BipinMandava
Solution 2 Venkateswara Rao