- When using the AWS CLI, do not run
aws configureand put any AWS credentials on your EC2 instances.
- Attach IAM Roles with proper permissions to your instances instead.
AWS CLI on EC2 - The Bad Way
When using the AWS CLI on an EC2 instance for accessing AWS resources like your S3 buckets(S3 is a storage provider on AWS),
you might encounter a permission error and prompted to run
aws configure as shown here:
You can follow their instructions and simply populate the AWS Access Key Id and AWS Secret Key Id with your own credentials or from another IAM User’s credentials and that should work as it gives the instance proper permissions to your AWS resources:
However, that is misleading. For our local computers that’s how we configure the AWS CLI but for EC2 instances that is a bad way of configuring the cli and it is insecure.
Why you should NOT put AWS credentials on an EC2
- An AWS credential is a personal credential and they are personal and should only be on your personal computer.
- If the EC2 is ever compromised, so would your personal account.
- If the EC2 is shared, other people may perform AWS CLI actions while impersonating you as it can be easily viewed as shown here:
- When using the AWS CLI on an EC2, a better way is to use IAM Roles(Identity and Access Management for AWS resources).
Attach an IAM Role to an EC2 instance
- Create an IAM Role.
- Select type of trusted entity: AWS service.
- Choose EC2 as the use case.
- Attach the minimum permissions to the IAM Role.
- Attach AmazonS3ReadOnlyAccess as we only want read access to S3 in this example.
Add Tags to the IAM Role (Optional).
- Finish creating the IAM Role.
- Give the IAM Role a name and click Create Role.
- Attaching the IAM Role to an EC2 instance.
- Right Click on an EC2 instance and find the option Security -> Modify IAM role.
- Attach the IAM Role to the EC2 instance.
- Note: This change can take a couple of seconds or minutes to reflect on the EC2 instance.
Test IAM Role on EC2
Running AWS CLI command now returns the expected response, showing a list of s3 buckets.
Check EC2 access on resources it does not have permissions to access.
AWS CLI on EC2 - The Right Way
And so in this way we can see that the EC2 instance has now the minimum permissions we want without having to put in any AWS credentials. See you next time!