Creating an S3 Bucket with Explicit Credentials
The code snippet below demonstrates how to configure an S3 client using explicit credentials. The application conditionally adds credentials if a secret access key is provided. It retrieves the bucket name from a command-line argument and then creates the bucket using the S3 API.ls and cat index.js on the instance.
When you execute the application with:
Handling Authentication Errors
When you first run the application with provided (but incorrect) credentials, you might see an error like:This error indicates that the access key ID is invalid. Before using IAM roles, our application used explicit access keys. For demonstration purposes, we then generated valid credentials by creating an IAM user.

Creating an IAM User and Generating Credentials
To generate valid credentials, follow these steps:- Navigate to the IAM console and create a new user named “SDK demo.”
- Attach policies directly by searching for and selecting Amazon S3 Full Access.
- In the Security Credentials tab for the new user, create an access key. For this lesson, choose the Command Line Interface (CLI) option, then click “Next” and “Create Access Key.”




Transitioning to IAM Roles
To remove the need for managing access keys manually, we now transition to using IAM roles. When you remove credentials from your code and run the application, you’ll encounter an “InvalidAccessKeyId” error, as expected. To resolve this, create an IAM role for the EC2 instance by following these steps:- In the IAM console, select Roles and click Create Role.
- Choose AWS service as the trusted entity type, since the role will be used by an EC2 instance.
- For the use case, select EC2 so the instance can perform actions on your behalf—specifically, interacting with S3.


- Attach the Amazon S3 Full Access policy to the role.
- Name the role (e.g., “AWS SDK S3”) and use the following trust policy:




Summary
There are two primary methods for authenticating an application with AWS services:
Using IAM roles simplifies security management by allowing your EC2 instance to assume a role with the correct permissions—enabling seamless interactions with AWS services like S3.
This lesson demonstrated the transition from explicit credentials to using IAM roles, enhancing your application’s security posture while reducing manual credential management.