Hardcoding IAM user credentials on an EC2 instance is a well-known anti-pattern for several reasons. First, static access keys do not rotate automatically, so a leaked key remains valid until someone notices and revokes it manually. Second, keys stored in environment variables, config files, or code often end up in version control or AMI snapshots, creating a permanent credential leak. Third, the blast radius of a compromise is tied to the key owner, not the instance, so you cannot easily scope the damage to one host.
The correct approach is to attach an IAM instance profile to the EC2 instance. An instance profile is a container for an IAM role. When the instance starts, the EC2 Instance Metadata Service (IMDS) provides temporary, automatically rotated credentials via STS AssumeRole under the hood. The AWS SDKs pick these up from the metadata endpoint automatically, so no credential is ever written to disk.
Create an IAM role with a trust policy that allows the EC2 service principal to assume it, attach an identity-based policy granting only s3:GetObject on the specific bucket and prefix, and associate the role with the instance at launch or attach it afterward. IMDSv2 should be enforced (requiring a session token) to prevent SSRF attacks from stealing the metadata credentials. The instance never holds a long-lived secret, and if the instance is terminated the credentials die with it.
Insider read
Really testing: Whether you understand the difference between IAM users (long-lived identities with static keys) and IAM roles (assumable identities with temporary credentials), and why temporary credentials are the correct primitive for workloads.
The tell: Candidates who say "just use an IAM user but rotate the keys regularly" are still wrong. Rotation reduces risk but does not eliminate the fundamental problem of static credentials living on a machine. The right answer kills static credentials entirely.
Follow-up: The instance is behind a proxy that rewrites outbound requests. An attacker uses SSRF to hit the metadata endpoint and steal the instance role credentials. How do you prevent that?
Say thisEC2 workloads should never hold static IAM credentials: use instance profiles, which deliver temporary STS credentials through IMDS, and enforce IMDSv2 to close the SSRF vector.