User guide

5. On the Set Permissions page, under Select Policy Template, select Amazon S3 Read Only
Access. Click Next Step.
6. On the Review page, click Create Role.
Launch an EC2 Instance and Specify Your IAM Role
You can launch an EC2 instance with an IAM role using the Amazon EC2 console or the SDK for Java.
To launch an EC2 instance using the console, follow the directions in Launch an EC2 Instance in the
Amazon EC2 User Guide for Linux Instances. When you reach the Review Instance Launch page,
click Edit instance details. In IAM role, specify the IAM role that you created previously. Complete
the procedure as directed. Notice that you'll need to create or use an existing security group and key
pair in order to connect to the instance.
To launch an EC2 instance with an IAM role using the SDK for Java, see Run an Amazon EC2
Instance (p. 29).
Create your Application
Let's build the sample application to run on the EC2 instance. First, create a directory that you can use
to hold your tutorial files (for example, GetS3ObjectApp).
Next, copy the SDK for Java libraries into your newly-created directory. If you downloaded the SDK for
Java to your ~/Downloads directory, you can copy them using the following commands:
cp -r ~/Downloads/aws-java-sdk-1.7.5/lib .
cp -r ~/Downloads/aws-java-sdk-1.7.5/third-party .
Open a new file, call it GetS3Ojbect.java, and add the following code:
import java.io.*;
import com.amazonaws.auth.*;
import com.amazonaws.services.s3.*;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
public class GetS3Object {
private static String bucketName = "text-content";
private static String key = "text-object.txt";
public static void main(String[] args) throws IOException
{
AmazonS3 s3Client = new AmazonS3Client();
try
{
System.out.println("Downloading an object");
S3Object s3object = s3Client.getObject(
new GetObjectRequest(bucketName, key));
displayTextInputStream(s3object.getObjectContent());
}
catch(AmazonServiceException ase)
{
System.out.println( "AmazonServiceException" );
Version v1.0.0
32
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances