I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

In the previous article, we’re focusing on S3; now we’ll focus on the Elastic Compute Cloud – commonly known as EC2.

1. EC2 Metadata Access

The AWS EC2MetadataUtils class provides static methods to access instance metadata like AMI Id and instance type. With Spring Cloud AWS we can inject this metadata directly using the @Value annotation.

This can be enabled by adding the @EnableContextInstanceData annotation over any of the configuration classes:

@Configuration
@EnableContextInstanceData
public class EC2EnableMetadata {
    //
}

In a Spring Boot environment, instance metadata is enabled by default which means this configuration is not required.

Then, we can inject the values:

@Value("${ami-id}")
private String amiId;

@Value("${hostname}")
private String hostname;

@Value("${instance-type}")
private String instanceType;

@Value("${services/domain}")
private String serviceDomain;

1.1. Custom Tags

Additionally, Spring also supports injection of user-defined tags. We can enable this by defining an attribute user-tags-map in context-instance-data using the following XML configuration:

<beans...>
    <aws-context:context-instance-data user-tags-map="instanceData"/>
</beans>

Now, let’s inject the user-defined tags with the help of Spring expression syntax:

@Value("#{instanceData.myTagKey}")
private String myTagValue;

2. EC2 Client

Furthermore, if there are user tags configured for the instance, Spring will create an AmazonEC2 client which we can inject into our code using @Autowired:

@Autowired
private AmazonEC2 amazonEc2;

Please note that these features work only if the app is running on an EC2 instance.

3. Conclusion

This was a quick and to-the-point introduction to accessing EC2d data with Spring Cloud AWS.

In the next article of the series, we’ll explore the RDS support.

Next »
Spring Cloud AWS – RDS
« Previous
Spring Cloud AWS – S3

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Lanre
Guest
Lanre

Hello baeldung, Am a great fan of your post and its been very helpful in my understanding of the spring ecosystem , Must confess i always watch out for your blog post on google search result. Just to help other user that might see this article series must especially those using spring boot note you have to include the below dependencies

// to utilise auto-configuration capabilities of spring boot
compile group: ‘org.springframework.cloud’, name: ‘spring-cloud-aws-autoconfigure’, version: ”
compile group: ‘org.springframework.cloud’, name: ‘spring-cloud-aws-context’, version: ”

Me
Admin
Me

I’m glad you’re enjoying the site Lanre.
Thanks for the notes here.
Cheers,
Eugen.