1. When using the AWS CLI, do not run aws configure and put any AWS credentials on your EC2 instances.
  2. 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: ec2-aws-configure

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: ec2-aws-keys

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: view-aws-creds
  • 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

  1. Create an IAM Role.
    • Select type of trusted entity: AWS service.
    • Choose EC2 as the use case. create-iam-trusted-entity
  2. Attach the minimum permissions to the IAM Role.
    • Attach AmazonS3ReadOnlyAccess as we only want read access to S3 in this example. iam-s3-permissions
  3. Add Tags to the IAM Role (Optional).

  4. Finish creating the IAM Role.
    • Give the IAM Role a name and click Create Role. create-iam-review
  5. 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. ec2-attach-iam
    • Note: This change can take a couple of seconds or minutes to reflect on the EC2 instance.

Test IAM Role on EC2

  1. Running AWS CLI command now returns the expected response, showing a list of s3 buckets. ec2-s3-access

  2. Check EC2 access on resources it does not have permissions to access. s3-make-bucket

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!