Home AWSAWS IAM Roles for EC2: Access S3 Without Stored Keys

AWS IAM Roles for EC2: Access S3 Without Stored Keys

by Knowledge Base Linux
AWS IAM Roles EC2 instance receiving temporary S3 access credentials

Storing long-lived AWS access keys on an EC2 instance is a risk that is easy to create and hard to notice. A key copied into a configuration file, baked into an AMI, or left in a shell history file can leak through a backup, a log file, or a compromised application, and it keeps working until someone remembers to revoke it. The safer pattern is to give the instance an identity of its own, and this guide shows how aws iam roles ec2 let an instance reach Amazon S3 with short-lived, automatically refreshed credentials and no stored keys at all.

AWS IAM Roles EC2 protected S3 bucket with role-based permissions

When an application running on the instance calls the AWS API, it does not present a fixed access key. Instead, it retrieves temporary credentials from the instance metadata service. Those credentials are tied to the role, expire after a short time, and are refreshed automatically by the AWS SDK or CLI. If the instance is terminated, its credentials die with it. There is nothing to store, and nothing for an attacker to reuse months later.

By the end of this guide, you will have created a role that only EC2 can assume, attached a least-privilege S3 policy to it, associated it with a running instance, and verified access from inside the instance. You will also learn how to rotate or remove the role safely and how to fix the most common errors.

Prerequisites

  • An AWS account with permission to manage IAM roles and EC2 instances (iam:CreateRole, iam:PutRolePolicy, ec2:AssociateIamInstanceProfile).
  • A running EC2 instance, for example Amazon Linux 2023 or Ubuntu 22.04 or 24.04, with AWS CLI version 2 installed.
  • An existing S3 bucket you want the instance to access, and the bucket name noted down.
  • Basic familiarity with the AWS Management Console and the AWS CLI.

Create an IAM Role for EC2

With aws iam roles ec2, an IAM role is an identity with permissions but no password or long-lived access key. The trust policy controls which service is allowed to assume the role. For EC2, the trusted principal is the ec2.amazonaws.com service. Save the following trust policy as trust-policy.json:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Create the role from the trust policy document:

aws iam create-role \
  --role-name ec2-s3-access-role \
  --assume-role-policy-document file://trust-policy.json

The console creates an instance profile with the same name automatically. From the CLI, you must create it yourself, because EC2 attaches a profile, not a role directly:

aws iam create-instance-profile \
  --instance-profile-name ec2-s3-access-profile

aws iam add-role-to-instance-profile \
  --instance-profile-name ec2-s3-access-profile \
  --role-name ec2-s3-access-role

Attach a Least-Privilege S3 Policy

A role without a permissions policy cannot do anything. Follow least privilege: grant only the actions the application needs, on one bucket. The following policy allows listing the bucket and reading and writing its objects. Replace example-bucket with your bucket name and save it as s3-policy.json:

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

Attach the policy to the role as an inline policy:

aws iam put-role-policy \
  --role-name ec2-s3-access-role \
  --policy-name ec2-s3-least-privilege \
  --policy-document file://s3-policy.json

Do not add s3:DeleteObject unless the application genuinely deletes objects, and never use s3:* on all resources as a shortcut. If the instance only reads files, drop s3:PutObject. For a quick read-only test, you could attach the AWS managed AmazonS3ReadOnlyAccess policy instead, but a scoped custom policy like the one above is the better production choice. Once access works, protecting the data itself is the next step, and our guide to S3 versioning and Object Lock explains how to guard objects against accidental overwrite and deletion.

Attach the Role to Your EC2 Instance

In the console, open EC2, select Instances, choose the instance, and go to Actions, then Security, then Modify IAM role. Select ec2-s3-access-role and confirm. From the CLI, associate the instance profile with the instance:

aws ec2 associate-iam-instance-profile \
  --instance-id i-0123456789abcdef0 \
  --iam-instance-profile Name=ec2-s3-access-profile

Confirm the association took effect:

aws ec2 describe-iam-instance-profile-associations \
  --filters Name=instance-id,Values=i-0123456789abcdef0

The association state should read associating and then associated. If the instance already has a different profile, replace the association with the replace-iam-instance-profile-association command, passing the existing association ID, or disassociate the old profile first.

Verify Access from the Instance

Connect to the instance over SSH and check which identity the CLI is using:

aws sts get-caller-identity

The output should show an assumed-role ARN, similar to arn:aws:sts::123456789012:assumed-role/ec2-s3-access-role/i-0123456789abcdef0. That ARN proves the instance is authenticating as the role, not as an IAM user. Next, list the bucket and copy a test file:

aws s3 ls s3://example-bucket/
aws s3 cp s3://example-bucket/test-file.txt ./test-file.txt
aws s3 cp ./test-file.txt s3://example-bucket/test-file.txt

If all three commands succeed, the role, policy, and association are working. This is the core benefit of aws iam roles ec2: the application never handles a fixed key. Before you call the job done, check that no static credentials are shadowing the role. Environment variables and a credentials file take precedence over role credentials, so grep env output for AWS and inspect ~/.aws/credentials if it exists, and remove any long-lived keys you find.

Temporary Credentials: How aws iam roles ec2 Deliver Them

The credentials your instance uses come from the Instance Metadata Service, or IMDS, at the link-local address 169.254.169.254. The AWS CLI and SDKs fetch them automatically, but you can inspect the flow yourself. IMDSv2 requires a session token, which you request with a PUT request and then pass as a header:

TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")

curl -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/

That request returns the role name; appending it returns the temporary key, secret, and session token. Never copy those values into application code: they expire within hours and the SDK refreshes them automatically. For the strongest posture, require IMDSv2 so the older token-free IMDSv1 path cannot be used:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required \
  --http-endpoint enabled

One caveat applies to containers: the default IMDS hop limit of 1 means a token request from inside a Docker container usually fails, because the packet crosses an extra network hop. Raise the hop limit to 2 for container workloads on the instance:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-put-response-hop-limit 2

For a deeper treatment of the EC2 role model, see the official AWS documentation on IAM roles for EC2, which covers instance profiles, trust policies, and credential retrieval in full.

Rotate or Remove aws iam roles ec2 Access

With aws iam roles ec2, role credentials rotate automatically, so there is no key rotation chore to schedule. Rotating in this context means changing what the role can do or swapping the role itself. To reduce permissions, edit the inline policy with a new put-role-policy call. To swap roles, replace the instance profile association as described above, and confirm the new identity with aws sts get-caller-identity before deleting anything old.

To remove the role from an instance entirely, disassociate the profile, then remove the role from the profile and delete the profile and role:

aws ec2 disassociate-iam-instance-profile \
  --association-id iip-assoc-0123456789abcdef0

aws iam remove-role-from-instance-profile \
  --instance-profile-name ec2-s3-access-profile \
  --role-name ec2-s3-access-role

aws iam delete-instance-profile \
  --instance-profile-name ec2-s3-access-profile

aws iam delete-role --role-name ec2-s3-access-role

Delete the role only after every instance using it has moved to another profile. Deleting an attached role leaves the instance without credentials and breaks applications depending on S3 access.

Troubleshooting

AccessDenied on S3 operations

First, confirm the aws iam roles ec2 identity with aws sts get-caller-identity. If the ARN shows a different role or an IAM user, the instance is not using the role you think it is. Next, check the policy ARNs: ListBucket must target the bucket ARN without a trailing wildcard, while GetObject and PutObject must target the bucket ARN with /*. Also check for an explicit deny in the bucket policy, which overrides any allow, and allow a short time for policy changes to propagate.

Unable to locate credentials or role not applied

Run describe-iam-instance-profile-associations and confirm the state is associated. If it is missing, the attach step failed or targeted the wrong instance ID. If the association exists but credentials are missing, look for AWS_ACCESS_KEY_ID in the environment or ~/.aws/credentials, which override the role. Also confirm the trust policy allows ec2.amazonaws.com to assume the role.

IMDS token errors from containers

A 401 response from the metadata service usually means the IMDSv2 token expired or was never requested, so request a fresh token as shown above. If the request fails only inside a container, raise the hop limit to 2. At scale, consider an ECS task role or EKS pod identity instead, since those scope credentials to the workload rather than the whole host.

Access still works after removing the role

Temporary credentials remain valid until they expire, so access may continue briefly after disassociation. This is expected, not a failed removal. Wait out the credential lifetime, then test again.

Conclusion

With aws iam roles ec2, you remove a whole class of credential leaks from your workloads. The role carries only the S3 permissions the application needs, its credentials expire and refresh on their own, and removing access is a single disassociation instead of a hunt through configuration files. Build the role with a scoped policy, verify the assumed-role identity from the instance, and require IMDSv2. Once uploads are flowing, you can also tune what happens to those objects over time, and our guide to S3 lifecycle rules and storage costs shows how to move aging objects to cheaper storage classes automatically.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.