7
votes

In order to publish messages to SNS I need to assume the correct role, so when using AWS SDK I create an AmazonSNS bean like this:

@Bean
public AmazonSNS amazonSnsClient(
        @Value("${cloud.aws.credentials.accessKey}") String accessKey,
        @Value("${cloud.aws.credentials.secretKey}") String secretKey,
        @Value("${cloud.aws.role.publisherArn}") String publisherRoleArn
) {
    AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();
    STSAssumeRoleSessionCredentialsProvider credentialsProvider = new STSAssumeRoleSessionCredentialsProvider
            .Builder(publisherRoleArn, SESSION_NAME)
            .withStsClient(stsClient)
            .build();
    return AmazonSNSClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(credentialsProvider)
            .build();
}

I'm trying to do the same with Spring Cloud AWS Messaging & Autoconfiguration but so far I didn't find any info on the topic. My application.yml looks like this

cloud:   
    aws:
        credentials:
            accessKey: ***
            secretKey: ***
            instanceProfile: true
        region:
            static: eu-central-1

Is it supported by Spring and I just didn't manage to find it or should I just stick to AWS SDK?

1

1 Answers

3
votes

Looks like there is no out-of-the-box solution for that. The easiest workaround is to create your own AWSCredentialsProvider bean

@Configuration
public class AwsCredentials {

    private static final String SESSION_NAME = "TestConsumer";

    @Bean
    @Primary
    public AWSCredentialsProvider credentialsProvider(
            @Value("${cloud.aws.credentials.accessKey}") String accessKey,
            @Value("${cloud.aws.credentials.secretKey}") String secretKey,
            @Value("${cloud.aws.role}") String role ) {

        AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(EU_CENTRAL_1)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();
        return new STSAssumeRoleSessionCredentialsProvider
            .Builder(role, SESSION_NAME)
            .withStsClient(stsClient)
            .build();
    }
}