Sub topic 14
Giving instances permissions with IAM roles
Programs on an EC2 instance often need to call AWS APIs. They might read an S3 object, write a CloudWatch metric, or fetch a secret. This chapter shows how to grant those permissions without putting access keys on the instance.
This chapter assumes you can launch an instance with the AWS CLI (covered earlier) and that you know what an IAM policy is. It also assumes you know what the instance metadata service is. The next chapter covers that service in detail.
Why not store access keys on the instance
You could run aws configure on the instance and paste in an IAM user's access key. This is a bad idea for several reasons.
- Long-lived keys stay valid until someone rotates them. If they leak, the leak can go unnoticed for months.
- Keys written to disk end up in AMIs, snapshots, shell history, and backups.
- Each instance and each rotation needs manual work.
An IAM role avoids these problems. A role is an IAM identity with permission policies attached, but with no password or permanent keys. Anything that is allowed to assume the role receives temporary credentials instead.
The parts: role, trust policy, permissions policy, instance profile
Four pieces work together.
| Piece | Purpose |
|---|---|
| Role | The identity that holds permissions. |
| Trust policy | States who may assume the role. For EC2, the principal is `ec2.amazonaws.com`. |
| Permissions policy | States what the role may do, such as `s3:GetObject` on one bucket. |
| Instance profile | A container that passes one role to an instance at launch. |
The instance profile is the piece people most often forget. An instance profile holds at most one role, and it is the object you attach to an instance. The AWS console creates the profile for you with the same name as the role. The CLI and most infrastructure tools do not, so you create it yourself.
How credentials reach the application
The instance does not receive a key file. Instead, the instance metadata service (IMDS) at 169.254.169.254 serves temporary credentials for the role. They consist of an access key ID, a secret key, and a session token. AWS rotates them automatically before they expire, usually several hours after issue.
The AWS CLI and the AWS SDKs look in this place automatically as part of their default credential lookup. The code on the instance needs no configuration.
Create a role and attach it at launch
The following script creates a role that can read objects from one bucket. It then wraps the role in an instance profile and launches an instance with that profile. Replace my-example-bucket and the placeholder IDs with your own values.
cat > trust-policy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
EOF
cat > s3-read.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::my-example-bucket/*"
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": "arn:aws:s3:::my-example-bucket"
}
]
}
EOF
aws iam create-role \
--role-name tutorial-web-role \
--assume-role-policy-document file://trust-policy.json
aws iam put-role-policy \
--role-name tutorial-web-role \
--policy-name s3-read \
--policy-document file://s3-read.json
aws iam create-instance-profile \
--instance-profile-name tutorial-web-profile
aws iam add-role-to-instance-profile \
--instance-profile-name tutorial-web-profile \
--role-name tutorial-web-role
aws ec2 run-instances \
--image-id "$AMI_ID" \
--instance-type t3.micro \
--key-name my-key \
--security-group-ids sg-0123456789abcdef0 \
--subnet-id subnet-0123456789abcdef0 \
--metadata-options HttpTokens=required \
--iam-instance-profile Name=tutorial-web-profile \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=tutorial-web}]'Two details in the policy matter. s3:GetObject applies to objects, so its resource ends in /*. s3:ListBucket applies to the bucket itself, so its resource has no suffix. Mixing these up is a common cause of AccessDenied errors.
Verify the role on the instance
After connecting over SSH, ask the CLI which identity it is using.
aws sts get-caller-identity
aws s3 ls s3://my-example-bucket/The first command returns an ARN that contains assumed-role/tutorial-web-role. If it shows an IAM user or reports no credentials, the instance has no profile or the profile is not working.
If a freshly created profile is rejected at launch, wait a few seconds and retry. IAM changes propagate with a short delay, so the launch can fail with an "invalid IAM instance profile" error even though the commands succeeded.
Change the role on a running instance
You do not need to stop an instance to change its role. You can attach, swap, or remove a profile while it runs.
aws ec2 describe-iam-instance-profile-associations \
--filters Name=instance-id,Values=i-0123456789abcdef0
aws ec2 replace-iam-instance-profile-association \
--association-id iip-assoc-0123456789abcdef0 \
--iam-instance-profile Name=tutorial-web-profileAn instance has at most one profile association at a time. Use associate-iam-instance-profile if the instance has none yet.
Editing the permissions policy on the role takes effect without any change to the instance. Credentials already issued stay valid until they expire, but each API call is evaluated against the role's current policies. A policy change therefore applies quickly.
Common errors and gotchas
- Too broad permissions. Avoid
AdministratorAccessor"Resource": "*"on instance roles. Anyone who gains code execution on the instance gets everything the role allows. Scope actions and resources to what the workload needs. - Stale keys override the role. The default credential chain checks environment variables and
~/.aws/credentialsbefore IMDS. If an old key file exists on the instance, it wins over the role. Remove it. - IMDS hop limit in containers. The default response hop limit of 1 can block containers from reaching IMDSv2. If a containerized process cannot get credentials, raise the limit with
aws ec2 modify-instance-metadata-options --instance-id i-0123456789abcdef0 --http-put-response-hop-limit 2. - IMDSv1 requests fail. With
HttpTokens=required, only token-based requests work. Old tools that use plaincurlagainst IMDS get a 401 error. Update the SDK or tool. - Role confusion. The role's trust policy controls who can assume it. The separate
iam:PassRolepermission controls who may attach it to an instance. A user who launches instances needsiam:PassRolefor that role, orrun-instancesfails with an authorization error.
Cleanup
Roles and profiles cost nothing, but remove them when finished to keep the account tidy. Delete them in this order: remove the role from the profile, delete the profile, delete the inline policy, then delete the role.
aws iam remove-role-from-instance-profile \
--instance-profile-name tutorial-web-profile \
--role-name tutorial-web-role
aws iam delete-instance-profile --instance-profile-name tutorial-web-profile
aws iam delete-role-policy --role-name tutorial-web-role --policy-name s3-read
aws iam delete-role --role-name tutorial-web-roleExercise
You launched an instance with a role that allows s3:GetObject on arn:aws:s3:::my-example-bucket/*. A script on the instance runs aws s3 ls s3://my-example-bucket/ and fails with AccessDenied, although aws s3 cp s3://my-example-bucket/file.txt . works. What is wrong and how do you fix it?
Show answer
Listing a bucket needs s3:ListBucket, which applies to the bucket ARN (arn:aws:s3:::my-example-bucket) and not to the objects. The role only grants s3:GetObject on objects. Add a statement allowing s3:ListBucket on arn:aws:s3:::my-example-bucket, for example with put-role-policy. The change applies without restarting the instance.
Exercise
A developer finds that an instance with a role attached still uses the permissions of an old IAM user. The instance has the role, and the role's policy is correct. What is the most likely cause?
Show answer
Static credentials exist on the instance, such as AWSACCESSKEY_ID environment variables or a ~/.aws/credentials file. The default credential chain checks those before IMDS, so they override the role. Remove them and confirm with aws sts get-caller-identity that the ARN shows assumed-role.