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

poze 4 months ago301 gadeen

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 4 months ago

1 Repons

8
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 4 months ago

Sign in and verify your email to post an answer.