Due to available tinkering time, this process will be documented in a series of smaller blog entries...
Amazon AWS provides for a mechanism within EC2 to automatically generate API credentials tied to IAM roles. Basically, this is just a long-winded way to say that they've implemented something to replace embedded passwords (access key, secret key or AK/SK).
The first step in this process will be to generate a simple Java-based client which connects to S3 and lists the contents of a given bucket. This application will initially use an AwsCredentials.properties file to test locally. In Part II, we will remove the credentials file and deploy the application to a running EC2 instance using a role with S3 access to verify success.
The initial application file is listed below:
package chris;
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class Application
{
public void listObjects(AmazonS3 s3Client, String bucketName)
{
ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName);
ObjectListing objectListing = s3Client.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries())
{
System.out.println(objectSummary.getKey() + " (size: " + objectSummary.getSize() + ")");
}
}
public void run()
{
Region region = Region.getRegion(Regions.US_EAST_1);
String bucketName = "SPARETIMENOTEBOOK";
try
{
// USE THE FOLLOWING LOCALLY WITH AWSCREDENTIALS.PROPERTIES FILE PRESENT
AmazonS3Client s3Client = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
// USE THE FOLLOWING ON PRODUCTION EC2 INSTANCE
// AmazonS3Client s3Client = new AmazonS3Client();
s3Client.setRegion(region);
listObjects(s3Client, bucketName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Application app = new Application();
app.run();
}
}
AwsCredentials.properties contains only the following:
secretKey=MY_SECRET_KEY_GOES_HERE
accessKey=MY_ACCESS_KEY_GOES_HERE
with the obvious inclusion of the actual key values...
After compilation, the class was observed running as expected and displays the contents of the given S3 bucket. In the next part, I will create an EC2 role and deploy the application to a running instance to verify the code runs properly without the included credentials.