User guide
1. In system environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
2. In the Java system properties: aws.accessKeyId and aws.secretKey.
3. In the default credentials file (the location of this file varies by platform).
4. In the instance profile credentials, which exist within the instance metadata associated with the IAM
role for the EC2 instance.
The final step in the default provider chain is available only when running your application on an EC2
instance, but provides the greatest ease of use and best security when working with EC2 instances.You
can also pass an InstanceProfileCredentialsProvider instance directly to the client constructor to get
instance profile credentials without proceeding through the entire default provider chain. For example:
AmazonS3 s3Client = new AmazonS3Client(new InstanceProfileCredentialsPro
vider());
When using this approach, the SDK will retrieve temporary AWS credentials that have the same
permissions as those associated with the IAM role associated with the EC2 instance in its instance profile.
Although these credentials are temporary and would eventually expire, InstanceProfileCredentialsProvider
will periodically refresh them for you so that the obtained credentials continue to allow access to AWS.
Important
The automatic credentials refresh happens only when you use the default client constructor,
which creates its own InstanceProfileCredentialsProvider as part of the default provider
chain, or when you pass an InstanceProfileCredentialsProvider instance directly to
the client constructor. If you use another method to obtain or pass instance profile credentials,
you are responsible for checking for and refreshing expired credentials.
If the client constructor can't find credentials using the credentials provider chain, it will throw an
AmazonClientException.
Walkthrough: Using IAM Roles for EC2 Instances
The following walkthrough uses an sample program that retrieves and object from Amazon S3 using an
IAM role to manage access.
Topics
• Create an IAM Role (p. 31)
• Launch an EC2 Instance and Specify Your IAM Role (p. 32)
• Create your Application (p. 32)
• Transfer the Compiled Program to Your EC2 Instance (p. 34)
• Run the Sample Program on the EC2 Instance (p. 34)
Create an IAM Role
Create an IAM role that grants read-only access to Amazon S3.
To create the IAM role
1. Open the IAM console.
2. In the navigation pane, click Roles, and then click Create New Role.
3. Enter a name for the role, and then click Next Step. Remember this name, as you'll need it when
you launch your EC2 instance.
4. On the Select Role Type page, under AWS Service Roles, select Amazon EC2.
Version v1.0.0
31
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances