Your app on EC2 authenticates to AWS using a long-lived access key baked into the AMI. What's the better pattern?
Short answer
A static key baked into an image leaks easily and lives forever, so the fix is to eliminate the long-lived credential entirely: attach an IAM role via an instance profile, which delivers short-lived, automatically rotated credentials with nothing embedded. Manual 90-day rotation still leaves a long-lived secret sitting in the AMI between rotations. Moving the key to an environment variable doesn't make it any less static or any less leaked. Emailing it to ops spreads the exposure to mailboxes and archives.
This question separates candidates who manage secrets from those who eliminate them. A long-lived key baked into an AMI is a textbook anti-pattern, and the strong answer removes the secret rather than babysitting it.
Why instance roles are the better pattern
When you attach an IAM role via an instance profile, the EC2 instance retrieves temporary credentials from the instance metadata service. AWS rotates them automatically, several times a day, and they expire on their own. There is no key to bake into the image, no key to leak in a snapshot, and no key to rotate by hand. If the instance is decommissioned, the credentials simply stop being issued. This shrinks both the likelihood of exposure and the lifetime of any exposure that does happen.
Why the distractors are weaker
- Rotate manually every 90 days. Rotation reduces the window, but between rotations you still have a long-lived, embedded secret. Anyone who copies the AMI, a snapshot, or the running disk gets a working key that may be valid for months. It also depends on a human remembering to do it.
- Store it in an environment variable. This changes where the static key lives, not the fact that it is static, embedded, and leakable. Env vars are if anything easier to dump (process listings, crash logs, child processes).
- Email it to ops. Now the secret lives in inboxes, sent folders, and mail archives across multiple people. This multiplies the exposure surface and is one of the worst things you can do with a credential.
What interviewers look for
The instinct to remove the long-lived credential instead of protecting it, plus understanding the mechanics: instance profile to role, temporary credentials from metadata, automatic rotation. Bonus for a realistic migration plan — attach the role, switch the SDK to default credential resolution, confirm it works, then revoke and delete the old key.
Likely follow-ups
- How does the instance actually obtain role credentials, and how often do they rotate?
- What's your migration plan to remove the baked-in key without an outage?
- How would you detect that a long-lived key has leaked or is being used from an unexpected location?