Sunday, September 08, 2013

Java Application Using AWS IAM Roles

Using AWS IAM roles prevents having to store credentials on your EC2 instances. More about the benefits here:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

Setting up your application and instance to use IAM roles is pretty easy.

1. Change your Java application to use these constructs wherever you are instantiating an AWS client for some service:

In the sample code you'll see instantiation of AWS clients for various services like this:

 AmazonSQS sqs = new AmazonSQSAsyncClient(
   new ClasspathPropertiesFileCredentialsProvider());
       

Replace the ClassPathPropertiesFileCredentialsProvider (which gets your AWS credentials from a file) with the InstanceProfileCredentialsProvider (which gets temporary security tokens from the service running on the EC2 instance).

 AmazonSQS sqs = new AmazonSQSAsyncClient(
   new InstanceProfileCredentialsProvider());  
 
2.Create a role which has the appropriate permissions. From services, choose IAM. Then choose Roles on the left and click Create New Role on the top as shown below. Give your role a name and click continue.



Add permissions to the role- choose Amazon EC2.


 Select service you want your EC2 instance to access.



Customize the policies if you need - continue.



And...Create Role



If you want to add additional permissions you can attach more policies.



3. Launch and instance and assign the role - assuming here you know how to launch an instance. That is covered in previous blog entries.



4. Copy your code up to the instance and run your application. If it worked with the security credential provider on your local machine with a file on the class path it should work with the instance security provider on the EC2 instance.