AWS IAM: how do I give my EC2 app access to S3 without hardcoding keys?

asked 4 months ago302 viewsen

7

My app on EC2 has AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in a .env file. A colleague said that's bad practice. What's the alternative?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 4 months ago

1 Answer

8
✓
✓ Accepted answer

Use an IAM role attached to the instance (an *instance profile*). The AWS SDKs automatically fetch temporary, auto-rotating credentials from the instance metadata service, so there are no keys to leak or rotate.

1. Create a role with the EC2 trust policy. 2. Attach a least-privilege policy:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["s3:GetObject", "s3:PutObject"],
    "Resource": "arn:aws:s3:::my-app-uploads/*"
  }]
}

3. Attach the role to the instance and delete the keys from .env (and deactivate them in IAM).

The SDK code doesn't change: new S3Client({}) finds the role credentials itself. The same idea applies elsewhere: ECS task roles, Lambda execution roles, EKS IRSA/Pod Identity. Also enforce IMDSv2 on the instance.

Sign in to tell others whether this worked.

answered 4 months ago

Sign in and verify your email to post an answer.