Menu
AWS SDK for .NET
Developer Guide

Granting Access Using an IAM Role

This .NET example shows you how to:

  • Create a sample program that retrieves an object from Amazon S3

  • Create an IAM role

  • Launch an Amazon EC2 instance and specify the IAM role

  • Run the sample on the Amazon EC2 instance

The Scenario

All requests to AWS must be cryptographically signed by using credentials issued by AWS. Therefore, you need a strategy to manage credentials for software that runs on Amazon EC2 instances. You have to distribute, store, and rotate these credentials securely, but also keep them accessible to the software.

IAM roles enable you to effectively manage AWS credentials for software running on EC2 instances. You create an IAM role and configure it with the permissions the software requires. For more information about the benefits of using IAM roles, see IAM Roles for Amazon EC2 in the Amazon EC2 User Guide for Windows Instances and Roles (Delegation and Federation) in the IAM User Guide.

To use the permissions, the software constructs a client object for the AWS service. The constructor searches the credentials provider chain for credentials. For .NET, the credentials provider chain is as follows:

  • The App.config file

  • The instance metadata associated with the IAM role for the EC2 instance

If the client doesn't find credentials in App.config, it retrieves temporary credentials that have the same permissions as those associated with the IAM role from instance metadata. The credentials are stored by the constructor on behalf of the application software, and are used to make calls to AWS from that client object. Although the credentials are temporary and eventually expire, the SDK client periodically refreshes them so that they continue to enable access. This periodic refresh is completely transparent to the application software.

The following examples show a sample program that retrieves an object from Amazon S3 using the AWS credentials you configure. You create an IAM role to provide the AWS credentials. Finally, you launch an instance with an IAM role that provides the AWS credentials to the sample program running on the instance.

Create a Sample that Retrieves an Object from Amazon S3

The following sample code requires a text file in an Amazon S3 bucket that you have access to, and AWS credentials that provide you with access to the Amazon S3 bucket.

For more information about creating an Amazon S3 bucket and uploading an object, see the Amazon S3 Getting Started Guide. For more information about AWS credentials, see Configuring AWS Credentials.

Copy
using System; using System.Collections.Specialized; using System.IO; using Amazon; using Amazon.S3; using Amazon.S3.Model; namespace Aws3Sample { class S3Sample { public static void Main(string[] args) { ReadS3File("bucket-name", "s3-file-name", "output-file-name"); Console.WriteLine("Press enter to continue"); Console.ReadLine(); } public static void ReadS3File( string bucketName, string keyName, string filename) { string responseBody = ""; try { using (var s3Client = new AmazonS3Client()) { Console.WriteLine("Retrieving (GET) an object"); var request = new GetObjectRequest() { BucketName = bucketName, Key = keyName }; using (var response = s3Client.GetObject(request)) using (var responseStream = response.ResponseStream) using (var reader = new StreamReader(responseStream)) { responseBody = reader.ReadToEnd(); } } using (var s = new FileStream(filename, FileMode.Create)) using (var writer = new StreamWriter(s)) { writer.WriteLine(responseBody); } } catch (AmazonS3Exception s3Exception) { Console.WriteLine(s3Exception.Message, s3Exception.InnerException); } } } }

To test the sample code

  1. Open Visual Studio and create an AWS Console project.

  2. Add the AWSSDK.S3 package to your project.

  3. Replace the code in the Program.cs file with the sample code.

  4. Replace the following values:

    bucket-name

    The name of your Amazon S3 bucket.

    s3-file-name

    The path and name of a text file in the bucket.

    output-file-name

    The path and file name to write the file to.

  5. Compile and run the sample program. If the program succeeds, it displays the following output and creates a file named s3Object.txt on your local drive that contains the text it retrieved from the text file in Amazon S3.

    Copy
    Retrieving (GET) an object

    If the program fails, be sure you're using credentials that provide you with access to the bucket.

  6. (Optional) Transfer the sample program to a running Windows instance on which you haven't set up credentials. Run the program and verify that it fails because it can't locate credentials.

Create an IAM Role

Create an IAM role that has the appropriate permissions to access Amazon S3.

To create the IAM role

You can use the Amazon EC2 console or the AWS SDK for .NET to launch an EC2 instance with an IAM role.

  • Using the console: Follow the directions in Launching a Windows Instance in the Amazon EC2 User Guide for Windows Instances. When you reach the Review Instance Launch page, choose Edit instance details. In IAM role, specify the IAM role you created previously. Complete the procedure as directed. You'll need to create or use an existing security group and key pair to connect to the instance.

  • Using the AWS SDK for .NET: See Launching an Amazon EC2 Instance.

An IAM user can't launch an instance with an IAM role without the permissions granted by the following policy.

Copy
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "iam:PassRole", "iam:ListInstanceProfiles", "ec2:*" ], "Resource": "*" }] }

To transfer the sample program to your EC2 instance, connect to the instance using the AWS Management Console as described in the following procedure.

Note

Alternatively, connect using the Toolkit for Visual Studio (see Connecting to an Amazon EC2 Instance in the AWS Toolkit for Visual Studio) and then copy the files from your local drive to the instance. The Remote Desktop session is automatically configured so that your local drives are available to the instance.

  1. Open the IAM console.

  2. In the navigation pane, choose Roles, and then choose Create New Role.

  3. Type a name for the role, and then choose Next Step. Remember this name because you'll need it when you launch your EC2 instance.

  4. Under AWS Service Roles, choose Amazon EC2. Under Select Policy Template, choose Amazon S3 Read Only Access. Review the policy, and then choose Next Step.

  5. Review the role information, and then choose Create Role.

To run the sample program on the EC2 instance

  1. Open the Amazon EC2 console.

  2. Get the password for your EC2 instance:

    1. In the navigation pane, choose Instances. Choose the instance, and then choose

    Connect.

    1. In the Connect To Your Instance dialog box, choose Get Password. (It will take a few minutes after the instance is launched before the password is available.)

    2. Choose Browse and navigate to the private key file you created when you launched the instance. Choose the file, and then choose Open to copy the file's contents into the contents box.

    3. Choose Decrypt Password. The console displays the default administrator password for the instance in the Connect To Your Instance dialog box, replacing the link to Get Password shown earlier with the password.

    4. Record the default administrator password or copy it to the clipboard. You need this password to connect to the instance.

  3. Connect to your EC2 instance:

    1. Choose Download Remote Desktop File. When your browser prompts you, save the .rdp file. When you finish, choose Close to close the Connect To Your Instance dialog box.

    2. Navigate to your downloads directory, right-click the .rdp file, and then choose Edit. On the Local Resources tab, under Local devices and resources, choose More. Choose Drives to make your local drives available to your instance. Then choose OK.

    3. Choose Connect to connect to your instance. You may get a warning that the publisher of the remote connection is unknown.

    4. Sign in to the instance when prompted, using the default Administrator account and the default administrator password you recorded or copied previously.

      Sometimes copying and pasting content can corrupt data. If you encounter a "Password Failed" error when you sign in, try typing in the password manually. For more information, see Connecting to Your Windows Instance Using RDP and Troubleshooting Windows Instances in the Amazon EC2 User Guide for Windows Instances.

  4. Copy the program and the AWS assemblies (AWSSDK.Core.dll and AWSSDK.S3.dll) from your local drive to the instance.

  5. Run the program and verify that it succeeds using the credentials provided by the IAM role.

    Copy
    Retrieving (GET) an object