Archive · AWS

IAM Roles for EC2: No Keys on Servers

Let an application call S3 using temporary credentials from an instance role.

1 min read

  • AWS IAM
  • Instance profile
  • AWS CLI 2.1

Access keys saved on a server can leak. An IAM role attached to the instance gives the software short-lived credentials that rotate automatically.

  1. Create a policy granting only what is needed:
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow",
    "Action": ["s3:GetObject", "s3:PutObject"],
    "Resource": "arn:aws:s3:::acme-app-assets-2020/uploads/*" }] }
  1. Create a role for EC2 with that policy, and attach it to the instance as an instance profile.
  2. On the server no configuration is needed:
aws sts get-caller-identity       # shows the role, not a user
aws s3 cp report.pdf s3://acme-app-assets-2020/uploads/

Software using an AWS SDK picks up the role automatically. Prefer specific actions and resource ARNs over s3:* on *. In 2021 consider requiring IMDSv2 on new instances (HttpTokens=required) to harden access to those credentials against SSRF attacks.