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

posée 4 months ago304 vuesen

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?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

1 réponse

8
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.