User guide

Using IAM Roles with the SDK for Java
If your application creates an AWS client using its default constructor (by providing the constructor with
no arguments), then the SDK for Java will search for credentials, in order, in the following places:
1. In the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
2. In the Java system properties aws.accessKeyId and aws.secretKey.
3. From the Instance Metadata Service (IMDS). The IMDS is what provides credentials using the IAM
role contained in the EC2 instance profile.
By default, if the AWS client constructor can't find credentials in the environment variables or in the Java
system properties, it will attempt to obtain temporary AWS credentials from the IMDS.These credentials
have the same permissions as the IAM role associated with the EC2 instance in its instance profile.
Note
The credentials provided by the IMDS are temporary and eventually expire, but the SDK for Java
client periodically refreshes them so that your application does not lose access to AWS. This
credential refesh is automatic and is transparent to your application; no actions need to be taken
by your application to refresh the credentials obtained through the IMDS.
You can tell the SDK for Java to use AWS credentials obtained from the IMDS first, before it attempts to
look for credentials in the environment or java system properties, by passing an
InstanceProfileCredentialsProvider object to the AWS client's constructor. For example, to create an S3
client using IMDS-supplied credentials:
AmazonS3 s3Client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
If the client constructor can't find credentials in the IMDS or through any of the other methods in the
credentials provider chain, an AmazonClientException will be thrown.
Note
AWS CloudFormation does not support calling its API with an IAM role.You must call the AWS
CloudFormation API as a regular IAM user.
Walkthrough: Using IAM Roles to Retrieve an Amazon S3
Object from an EC2 Instance
In this walkthrough, we'll show an example of a program that uses IAM roles for EC2 instances to manage
access.
Topics
Create the IAM Role (p. 30)
Launch an EC2 Instance with an Instance Profile (p. 32)
Create your Application (p. 33)
Transfer the Compiled Program to Your EC2 Instance (p. 35)
Run the Program (p. 35)
Create the IAM Role
We'll begin by creating an IAM role with appropriate permissions for our application.You can create an
IAM role in a number of different ways, including with the AWS CLI. For more information about each of
the ways to create roles, see Creating a IAM Role in IAM User Guide. We'll use the AWS Management
Console in this walkthrough, since you don't need to install anything to use it.
Version v1.0.0
30
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances