Home AWSAWS IAM Roles for EC2: Secure Keyless Access Guide

AWS IAM Roles for EC2: Secure Keyless Access Guide

by Knowledge Base Linux
AWS IAM roles EC2 secure keyless access with temporary badge

Setting up AWS IAM roles EC2 access is the correct way to give an instance access to AWS services, and they replace the dangerous habit of storing long-lived access keys on the server. An access key baked into a config file, an environment variable, or a git repository is a credential that never expires, travels wherever the file travels, and is hard to rotate without downtime. A role solves all three problems: the instance receives short-lived temporary credentials automatically, those credentials rotate on their own, and nothing secret is stored on disk. This guide creates a least-privilege role for an EC2 instance, attaches it through an instance profile, verifies it from inside the instance, and fixes the errors that most often confuse first-time setups.

The vocabulary matters, because three different objects are often confused. A role is an identity with a trust policy that says who may assume it, in this case the EC2 service. A policy is a document that says what the role may do, such as reading objects from one S3 bucket. An instance profile is the container that actually attaches a role to an instance: you cannot attach a role directly, you attach the profile, and the profile holds the role. The AWS CLI and SDKs on the instance find the credentials automatically through the instance metadata service, so application code needs no key handling at all. If you are new to AWS networking, our guide to AWS VPC endpoints for private S3 access pairs well with roles, because it keeps the S3 traffic itself off the public internet.

AWS IAM roles EC2 permission gate to cloud storage

Prerequisites

You need an AWS account with permission to create IAM roles and EC2 instances, the AWS CLI installed and configured on your workstation, and a running EC2 instance or the ability to launch one. The examples grant read access to a single S3 bucket; replace the bucket name with your own, and never test a new policy against a production bucket until you have proven it in a test bucket. You should also know whether your instance uses IMDSv2, because the credential retrieval steps differ, and modern Amazon Linux and Ubuntu images enforce IMDSv2 by default.

AWS IAM Roles EC2: Create a Least-Privilege Role

Create the role with a trust policy that allows only the EC2 service to assume it. Write the trust document to a file, create the role from that file, and then attach a policy that grants exactly the access the application needs. The example policy allows listing the bucket and getting objects from it, and nothing else: no writes, no deletes, and no access to other buckets. Least privilege is not a slogan here; it is the difference between a compromised instance reading one bucket and a compromised instance deleting your entire storage.

cat > trust.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
aws iam create-role --role-name AppS3Reader --assume-role-policy-document file://trust.json
cat > policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": "arn:aws:s3:::example-app-bucket"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::example-app-bucket/*"
    }
  ]
}
EOF
aws iam put-role-policy --role-name AppS3Reader --policy-name S3ReadOnly --policy-document file://policy.json

Note the two resources in the policy: ListBucket applies to the bucket itself, while GetObject applies to the objects inside it, which is why the second ARN ends with a wildcard path. Forgetting that distinction is the single most common reason a policy that looks right still denies access. The official AWS documentation on IAM roles for Amazon EC2 describes the trust and policy model in full, including the instance profile step that follows.

AWS IAM Roles EC2: Attach the Role and Verify Credentials

Attach the role through an instance profile, then associate that profile with the instance. If the instance is already running, you can attach a profile to it without stopping it, which makes adopting roles on existing fleets painless. Create the profile, add the role to it, and associate it with the instance by ID.

aws iam create-instance-profile --instance-profile-name AppS3ReaderProfile
aws iam add-role-to-instance-profile --instance-profile-name AppS3ReaderProfile --role-name AppS3Reader
aws ec2 associate-iam-instance-profile --instance-id i-0123456789abcdef0 --iam-instance-profile Name=AppS3ReaderProfile

Now verify from inside the instance. With IMDSv2, first request a session token, then request the credentials document. The response contains temporary access keys with an expiration time, and the AWS CLI uses this same mechanism automatically, so you never need to copy these keys anywhere. Test with an S3 command that should succeed and one that should fail: reading from your bucket should work, while writing to it, or reading from another bucket, should be denied. That negative test is what proves least privilege is real and not just documented.

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/
aws s3 ls s3://example-app-bucket/
aws s3 cp /tmp/test.txt s3://example-app-bucket/test.txt

The last command should fail with Access Denied, and that failure is the correct result. If it succeeds, the policy is broader than intended and you should review it before continuing. For monitoring the instances that use these roles, see our guide to monitoring EC2 with CloudWatch alarms, which covers the alerts that catch a role being used unexpectedly.

Troubleshooting

When the AWS CLI reports that it cannot find credentials, the role is usually not attached to the instance at all, or it is attached as a role rather than through an instance profile. Run describe-iam-instance-profile on the instance and confirm a profile is listed; a role created but never added to a profile, or a profile created but never associated, produces exactly this error. When the CLI finds credentials but S3 access is denied, use the IAM policy simulator or check the two-resource distinction above, and confirm the bucket name in the policy matches the bucket in the command, including the region if the bucket policy restricts it.

When metadata requests fail on a container running on the instance, the IMDS hop limit is the likely cause: the default hop limit of one means a container, which is one extra network hop, cannot reach the metadata service. Raise the hop limit to two with modify-instance-metadata-options, but do so deliberately, because a higher hop limit slightly weakens the metadata protection that IMDSv2 provides. When credentials work from the host but not from an application, check whether the application cached old credentials or reads a credentials file that overrides the role: the credential chain checks environment variables and config files before the metadata service, so a stale access key in the environment will shadow the role entirely. Remove the stale key and let the role take over.

Conclusion

AWS IAM roles EC2 setups turn credential management from a storage problem into a non-problem: create a role with a narrow trust policy, attach a least-privilege policy that distinguishes bucket from objects, attach it through an instance profile, and verify with both a positive and a negative test. Rotate nothing, store nothing, and audit the role usage in CloudTrail when you need to know who did what. The next time an application needs AWS access from an instance, the answer should be a role, not a key.

You may also like

KbLinux

Typically replies within a day

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