- Provide long-lived credentials (AWS access key + secret) to the application.
- Attach an IAM role (instance profile) to the EC2 instance so the SDK can authenticate automatically using temporary credentials.
Example application (cleaned up)
This Node.js example configures an S3 client and, if credentials are provided, sets them explicitly. The application reads the bucket name from the command line and attempts to create the bucket.1) Running the app on EC2 with no credentials (expected failure)
If neither the code nor the environment provides credentials, the AWS SDK cannot sign requests. The resulting authentication error confirms that valid credentials are required:2) Option A — Create an IAM user, generate access keys, and provide them to the app
One authentication method is to create an IAM user with the required permissions (for example,AmazonS3FullAccess), generate an access key pair, and place those values in the application or environment variables.
In the demo we created an IAM user and attached the AmazonS3FullAccess policy.


Hard-coding long-lived credentials in application source code is risky. Use environment variables, secrets managers, or better yet, IAM roles for compute resources to avoid credential leakage and manual rotation.
3) Remove the keys and verify the app fails (cleanup)
After deleting the bucket and removing the hard-coded credentials, running the app again demonstrates the same authentication failure because no valid credentials exist to sign the request:4) Option B (recommended) — Create an IAM role and attach it to the EC2 instance
Recommended approach: create an IAM role with the necessary permissions (for example, attachAmazonS3FullAccess) and make the trusted entity the EC2 service principal. Then attach that role to your EC2 instance as an instance profile. The AWS SDK will automatically retrieve temporary credentials from the instance metadata service and sign requests — no hard-coded keys required.
Example trust policy for a role trusted by EC2:
aws-sdk-s3), attach the AmazonS3FullAccess policy, then attach the role to your running instance:
- Console: Instances → Security → Modify IAM role → select your role → Update IAM role

Using IAM roles attached to compute resources (EC2, Lambda, ECS tasks) is the recommended way to grant AWS permissions to applications. Roles remove the need for long-lived credentials and support automatic credential rotation.
Comparison: Credentials vs IAM Role
Summary
- Providing access keys to applications works but is less secure and requires credential management.
- Assigning an IAM role (instance profile) to an EC2 instance allows the AWS SDK for JavaScript to authenticate automatically with short-lived credentials — this is the recommended approach for EC2-hosted applications.
- AWS SDK for JavaScript v3 documentation
- Amazon EC2 documentation
- Amazon S3 documentation
- AWS IAM best practices