Search code examples
javaamazon-web-servicesamazon-ec2amazon-sqs

How to authenticate between EC2 and SQS and local machine to SQS


I'm trying to authenticate with SQS on my local machine and on an EC2 instance. On my local machine I can successfully use a profile:

ProfileCredentialsProvider p = ProfileCredentialsProvider.builder().profileName("my-profile").build();

However, I'm not sure what I need to do to authenticate from the EC2, do I need to add an IAM role and give the EC2 permissions to SQS (I'm quite new to AWS Auth)?

I thought I could use InstanceProfileCredentialsProvider for the EC2 but that didn't work but that could be because I'm missing the Role permission step above?

SqsClient sqsClient = SqsClient.builder().credentialsProvider(p)
            .region(Region.US_WEST_2)
            .build();

I'm guessing but I think the final result will be:

ProfileCredentialsProvider p = ProfileCredentialsProvider.builder().profileName("my-profile").build();
InstanceProfileCredentialsProvider i = InstanceProfileCredentialsProvider.builder().build();
        
sqsClient = SqsClient.builder()
                    .credentialsProvider(p)
                    .credentialsProvider(i)
                    .region(Region.US_WEST_2)
                    .build();

I'm using the aws SDK Version 2 software.amazon.awssdk:sqs:2.17.24


Solution

  • For EC2 the preferred method is to assign an IAM role to the instance that has the required SQS permissions.

    I suggest reading how the default credential provider works. As long as you provide one of the credential methods the default credential provider looks for, you don't have to do anything special in your code to use those credentials.

    For example when your code is running on EC2 it can automatically pick up the IAM role assigned to the instance, and your code can look like this:

    sqsClient = SqsClient.builder().build();
    

    Note that no credentials providers are passed to the client. Also it will use the same region the EC2 instance is running in by default, so you don't need to pass the region either.


    For running locally you can simply set the AWS_PROFILE environment variable before running your code.