Instance Profile Credentials using Spring Cloud

1. Introduction

In this quick article, we’re going to build a Spring Cloud application that uses instance profile credentials to connect to an S3 bucket.

2. Provisioning Our Cloud Environment

Instance profiles are an AWS feature that allows EC2 instances to connect to other AWS resources with temporary credentials. These credentials are short-lived and are automatically rotated by AWS.

Users can only request temporary credentials from within EC2 instances. However, we can use these credentials from anywhere until they expire.

To get more help specifically on instance profile configuration, check out AWS’s documentation.

2.1. Deployment

First of all, we need an AWS environment that has the appropriate setup.

For the code sample below, we need to stand up an EC2 instance, an S3 bucket, and the appropriate IAM roles. To do this, we can use the CloudFormation template in the code sample or simply stand these resources up on our own.

2.2. Verification

Next, we should make sure our EC2 instance can retrieve instance profile credentials. Replace <InstanceProfileRoleName> with the actual instance profile role name:

curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<InstanceProfileRoleName>

If everything is setup correctly, then the JSON response will contain AccessKeyIdSecretAccessKeyToken, and Expiration properties.

3. Configuring Spring Cloud

Now, for our sample application. We need to configure Spring Boot to use instance profiles, which we can do in our Spring Boot configuration file:

cloud.aws.credentials.instanceProfile=true

And, that’s it! If this Spring Boot application is deployed in an EC2 instance, then each client will automatically attempt to use instance profile credentials to connect to AWS resources.

This is because Spring Cloud uses the EC2ContainerCredentialsProviderWrapper from the AWS SDK. This will look for credentials in priority order, automatically ending with instance profile credentials if it can’t find any others in the system.

If we need to specify that Spring Cloud only use instance profiles, then we can instantiate our own AmazonS3 instance.

We can configure it with an InstanceProfileCredentialsProvider and publish it as a bean:

@Bean
public AmazonS3 amazonS3() {
    InstanceProfileCredentialsProvider provider
      = new InstanceProfileCredentialsProvider(true);
    return AmazonS3ClientBuilder.standard()
      .withCredentials(provider)
      .build();
}

This will replace the default AmazonS3 instance provided by Spring Cloud.

4. Connecting to Our S3 Bucket

Now, we can connect to our S3 bucket using Spring Cloud as normal, but without needing to configure permanent credentials:

@Component
public class SpringCloudS3Service {

    // other declarations

    @Autowired
    AmazonS3 amazonS3;

    public void createBucket(String bucketName) {
        // log statement
        amazonS3.createBucket(bucketName);
    }
}

Remember that because instance profiles are only issued to EC2 instances, this code only works when running on an EC2 instance.

Of course, we can repeat the process for any AWS service that our EC2 instance connects to, including EC2, SQS, and SNS.

5. Conclusion

In this tutorial, we’ve seen how to use instance profile credentials with Spring Cloud. Also, we created a simple application that connects to an S3 bucket.

As always, the full source can be found over on GitHub.

Related posts:

Check if a String is a Palindrome in Java
Server-Sent Events in Spring
Properties with Spring and Spring Boot
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Perform Cryptography Using Transposition Technique
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
How to Remove the Last Character of a String?
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Spring Cloud – Securing Services
Immutable ArrayList in Java
Using Spring @ResponseStatus to Set HTTP Status Code
The Registration Process With Spring Security
Working with Kotlin and JPA
Encode/Decode to/from Base64
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Pagination and Sorting using Spring Data JPA
Supplier trong Java 8
Java Program to Find the Mode in a Data Set
Spring Boot Change Context Path
Java Program to Implement Sorted Doubly Linked List
A Custom Data Binder in Spring MVC
A Guide to HashSet in Java
Runnable vs. Callable in Java
Java Program to Check if a Matrix is Invertible
Hướng dẫn Java Design Pattern – Mediator
Write/Read cookies using HTTP and Read a file from the internet
Java Program to Perform String Matching Using String Library
ETL with Spring Cloud Data Flow
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Sử dụng Fork/Join Framework với ForkJoinPool trong Java