User guide
Walkthrough: Using IAM Roles to Retrieve an
Amazon S3 Object from an Amazon EC2 Instance
In this walkthrough, we consider a program that retrieves an object from Amazon S3 using regular
credentials. We then modify the program so that it uses IAM roles for Amazon EC2 Instances.
Sample Program with Credentials
Here is our starting program, which retrieves an object from an Amazon S3 bucket.The code as shown
here accesses your credentials by using the profile name stored in the project's App.config file.
using System;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
namespace s3.amazon.com.docsamples.retrieveobject
{
class S3Sample
{
static string bucketName = "text-content";
static string keyName = "text-object.txt";
static IAmazonS3 client;
public static void Main(string[] args) {
NameValueCollection appConfig = ConfigurationManager.AppSettings;
Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredPro
fileAWSCredentials("appConfig.AWSProfileName");
string responseBody;
try {
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
credentials, RegionEndpoint.USWest2)) {
Console.WriteLine("Retrieving (getting) an object");
GetObjectRequest request = new GetObjectRequest() {
BucketName = bucketName,
Key = keyName
};
using (GetObjectResponse response = client.GetObject(request)) {
using (Stream responseStream = response.ResponseStream) {
using (StreamReader reader = new StreamReader(responseStream)) {
responseBody = reader.ReadToEnd();
}
}
}
Version v2.0.0
33
AWS SDK for .NET Developer Guide
Walkthrough: Using IAM Roles to Retrieve an Amazon
S3 Object from an Amazon EC2 Instance