Skip to main content

Cloud and deployment · Intermediate · 22 min

Create an IAM role with a least-privilege policy for one app

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4

You will give an app on EC2 its own IAM role that can read and write objects under one prefix of one S3 bucket, capped by a permissions boundary, and prove from the instance that every other request is refused.

On this page

An app that uploads files needs AWS credentials. The quick way is an IAM user with an access key pasted into an .env file on the server, and a policy such as AmazonS3FullAccess so nothing fails on day one. That key never expires, and the policy lets anyone who reads the file delete every bucket in the account.

The better way has two parts. The app gets a role instead of a key, so EC2 hands it short-lived credentials that rotate on their own. And the role gets only the permissions the app uses: here, reading and writing objects under uploads/ in one bucket. Everything else, including the rest of the same bucket, stays refused by default.

In this tutorial you write that role from scratch: a trust policy that lets EC2 assume it, an inline policy scoped to one prefix, and a permissions boundary that caps what anyone can add later. You attach it to an instance through an instance profile, then log in to the instance and check both sides: the allowed calls work and the others come back AccessDenied. The last part shows how to tighten a role that started too broad, using IAM Access Analyzer.

IAM has no charge. The bucket costs a fraction of a cent for the few bytes you store, and the clean-up deletes it. Your EC2 instance bills while it runs, so stop or terminate it when you finish. IAM is global, so the role works the same whether the app runs in London, Virginia or Cape Town (af-south-1, an opt-in Region you must enable before use).

Commands are labelled on your laptop or on the instance. Names start with iam-app-demo and files live in ~/iam-app-demo, so nothing collides with what your account already has.

Step 1 · Write down what the app needs, then make the bucket

Least privilege starts on paper, not in JSON. For this app the list is short:

  • Upload a file to uploads/: s3:PutObject on objects uploads/* in one bucket.
  • Download a file from uploads/: s3:GetObject on the same objects.
  • List what is in uploads/: s3:ListBucket on the bucket itself, only for the uploads/ prefix.

Anything not on the list, such as deleting objects, listing your other buckets or reading private/ in the same bucket, should fail. If you later find the app needs s3:DeleteObject, you add that one action on purpose.

On your laptop, make a working folder and keep the account ID and a bucket name in variables. S3 bucket names are global across all AWS customers, so the account ID in the name keeps it unique:

Bash
mkdir -p ~/iam-app-demo
cd ~/iam-app-demo
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
BUCKET="iam-app-demo-${ACCOUNT_ID}"
echo "$BUCKET"

Create the bucket in your default Region, and put one file outside uploads/ so you have something the app must not read:

Bash
aws s3 mb "s3://${BUCKET}"
echo "not for the app" > notes.txt
aws s3 cp notes.txt "s3://${BUCKET}/private/notes.txt"

Check it worked

echo prints a name such as iam-app-demo-123456789012 with your account ID. aws s3 ls "s3://${BUCKET}/" --recursive lists one object, private/notes.txt.

Step 2 · Write the trust policy

A role has two policies that answer two questions. The trust policy answers "who may become this role?". The permissions policy answers "what may the role do?". Start with the first. Only the EC2 service should be able to assume this role:

Bash
cat > trust.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "LetEc2AssumeThisRole",
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
JSON
  • Principal is ec2.amazonaws.com, the EC2 service, not a person or account. EC2 assumes the role for each instance that carries it and serves the resulting credentials to programs on that instance.
  • There is no Resource line. A trust policy is attached to the role, so the role is the resource.
  • Nothing in it says which instance. That is decided by which instances you attach the role to, and attaching needs the iam:PassRole permission. Keep iam:PassRole for administrators, or anyone who can launch instances can borrow any role.

Check it worked

python3 -m json.tool trust.json prints the policy back, indented, with no error. A typo such as a missing comma shows as Expecting ',' delimiter with a line number.

Bash
python3 -m json.tool trust.json > /dev/null && echo "trust.json ok"

Step 3 · Write the permissions policy for one prefix

Now the permissions, built from the table in the first step. The file uses your bucket name, so the heredoc is unquoted and the shell fills in ${BUCKET}:

Bash
cat > uploads-access.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadAndWriteUploads",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::${BUCKET}/uploads/*"
    },
    {
      "Sid": "ListOnlyTheUploadsPrefix",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::${BUCKET}",
      "Condition": {
        "StringLike": { "s3:prefix": ["uploads/", "uploads/*"] }
      }
    }
  ]
}
JSON

Read it statement by statement:

  • ReadAndWriteUploads allows two object actions. Its Resource is an object ARN: the bucket name, a slash, then the key pattern. uploads/* matches uploads/a.jpg and uploads/2026/11/b.pdf, but not private/notes.txt and not a key called uploads with no slash.
  • ListOnlyTheUploadsPrefix allows listing. s3:ListBucket acts on the bucket, so its Resource is the bucket ARN with no slash. Put it under the object ARN and it never matches; that mix-up is behind many S3 policies that "do nothing".
  • The Condition narrows the listing. s3:prefix is the prefix the caller asks to list. StringLike allows * wildcards, so the app may list uploads/ and anything below it. A listing of the whole bucket sends no prefix, so the condition does not match, nothing allows the call, and it is refused.
  • There is no Deny. You do not need one: anything not allowed is refused by default. Explicit denies are for guard rails that must hold even if someone adds an Allow later, and the next step handles that a different way.

Check it worked

grep arn:aws:s3 uploads-access.json shows your real bucket name twice, not ${BUCKET}. The JSON check prints uploads-access.json ok.

Bash
python3 -m json.tool uploads-access.json > /dev/null && echo "uploads-access.json ok"
grep -c "arn:aws:s3:::${BUCKET}" uploads-access.json

Step 4 · Create the role with a permissions boundary

A permissions boundary is a managed policy set on a role as an upper limit. The role's effective permissions are what its own policies allow and the boundary allows. A boundary grants nothing by itself. Its job is the future: if a teammate in a hurry attaches AmazonS3FullAccess to this role next year, the boundary still keeps the app inside this one bucket.

Write a boundary that allows any S3 action, but only on this bucket and its objects:

Bash
cat > boundary.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "NeverBeyondTheAppBucket",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::${BUCKET}",
        "arn:aws:s3:::${BUCKET}/*"
      ]
    }
  ]
}
JSON
BOUNDARY_ARN=$(aws iam create-policy --policy-name iam-app-demo-boundary \
  --description "Upper limit for the iam-app-demo role: one bucket only" \
  --policy-document file://boundary.json \
  --query Policy.Arn --output text)
echo "$BOUNDARY_ARN"

Create the role with the trust policy and the boundary, then add the permissions as an inline policy:

Bash
aws iam create-role --role-name iam-app-demo-role \
  --description "Uploads app on EC2: read and write uploads/ in one bucket" \
  --assume-role-policy-document file://trust.json \
  --permissions-boundary "$BOUNDARY_ARN" \
  --query Role.Arn --output text
aws iam put-role-policy --role-name iam-app-demo-role \
  --policy-name uploads-access \
  --policy-document file://uploads-access.json

An inline policy lives inside one role and is deleted with it. That suits a policy written for exactly one app: nobody can attach it to another role by accident, and there is no orphaned policy left behind when the app is retired. When several roles need the same permissions, use a customer managed policy instead.

Check it worked

create-role prints an ARN such as arn:aws:iam::123456789012:role/iam-app-demo-role. These two commands show the boundary and the inline policy:

Bash
aws iam get-role --role-name iam-app-demo-role \
  --query 'Role.PermissionsBoundary.PermissionsBoundaryArn' --output text
aws iam list-role-policies --role-name iam-app-demo-role --query 'PolicyNames' --output text

The first prints your iam-app-demo-boundary policy ARN and the second prints uploads-access. aws iam list-attached-role-policies --role-name iam-app-demo-role shows an empty list: the boundary is not an attached policy and grants nothing on its own.

Step 5 · Attach the role to the instance through an instance profile

EC2 does not take a role directly. It takes an instance profile, a small wrapper that holds one role. Create one, put the role in it, then attach it to your instance.

On your laptop, set INSTANCE_ID to your instance's ID first, for example export INSTANCE_ID=i-0123456789abcdef0 (replace it with yours; aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,State.Name]' --output text lists them). Then run:

Bash
aws iam create-instance-profile --instance-profile-name iam-app-demo-profile \
  --query InstanceProfile.Arn --output text
aws iam add-role-to-instance-profile --instance-profile-name iam-app-demo-profile \
  --role-name iam-app-demo-role

IAM changes take a few seconds to reach every AWS endpoint. If the next command fails with Invalid IAM Instance Profile name, wait ten seconds and run it again:

Bash
aws ec2 associate-iam-instance-profile --instance-id "$INSTANCE_ID" \
  --iam-instance-profile Name=iam-app-demo-profile \
  --query 'IamInstanceProfileAssociation.State' --output text

An instance holds one profile at a time. If yours already has one, this fails with IncorrectState; swap it with aws ec2 replace-iam-instance-profile-association instead, and remember any app relying on the old role loses those permissions.

Check it worked

The association starts as associating and then becomes associated:

Bash
aws ec2 describe-iam-instance-profile-associations \
  --filters Name=instance-id,Values="$INSTANCE_ID" \
  --query 'IamInstanceProfileAssociations[].[State,IamInstanceProfile.Arn]' --output text

The output shows associated and the ARN of iam-app-demo-profile.

Step 6 · Prove the app's access from the instance

Now act as the app. SSH to your instance. On the instance, make sure no old keys are in the way: if ~/.aws/credentials exists there, or AWS_ACCESS_KEY_ID is set, the CLI uses those first and you are not testing the role. Then set the bucket name and Region (replace both with yours; the Region is where you made the bucket), for example export BUCKET=iam-app-demo-123456789012 and export AWS_DEFAULT_REGION=eu-west-2.

Ask AWS who you are:

Bash
aws sts get-caller-identity --query Arn --output text

The answer is arn:aws:sts::<account>:assumed-role/iam-app-demo-role/<instance-id>. The CLI found no keys, asked the instance metadata service, and received temporary credentials for the role. EC2 refreshes them before they expire; your app's SDK does the same lookup, so the app's configuration holds no secret at all.

Try the three things the app should be able to do:

Bash
echo "hello from the app" > hello.txt
aws s3api put-object --bucket "$BUCKET" --key uploads/hello.txt --body hello.txt --query ETag --output text
aws s3api get-object --bucket "$BUCKET" --key uploads/hello.txt downloaded.txt --query ContentLength --output text
cat downloaded.txt
aws s3api list-objects-v2 --bucket "$BUCKET" --prefix uploads/ --query 'Contents[].Key' --output text

Then the things it should not. Each of these should fail:

Bash
aws s3api put-object --bucket "$BUCKET" --key private/hello.txt --body hello.txt
aws s3api get-object --bucket "$BUCKET" --key private/notes.txt stolen.txt
aws s3api list-objects-v2 --bucket "$BUCKET"
aws s3api list-buckets
aws iam list-roles

Check it worked

The allowed calls print an ETag in quotes, the size 19, the line hello from the app and the key uploads/hello.txt. Each refused call prints something like An error occurred (AccessDenied) when calling the PutObject operation: User: arn:aws:sts::...:assumed-role/iam-app-demo-role/... is not authorized to perform: s3:PutObject ... because no identity-based policy allows the s3:PutObject action, and no stolen.txt appears. The listing without --prefix is refused because of the s3:prefix condition; list-buckets and list-roles are refused because no statement mentions them at all.

Step 7 · Tighten a role that started too broad

You knew this app's needs in advance. Often you do not: an existing app runs with a wide policy and nobody remembers what it calls. AWS's advice is to start from what works, then cut back using what the role actually did. IAM Access Analyzer can draft that policy from your CloudTrail logs.

It needs three things in your account: a CloudTrail trail that logs the account's events, a service role that lets Access Analyzer read that trail (the console offers to create one the first time), and a date range of up to 90 days. On your laptop, write the request and start the job (replace the trail ARN, the service role ARN and the start time with your own):

Bash
cat > trail.json <<'JSON'
{
  "accessRole": "arn:aws:iam::123456789012:role/service-role/AccessAnalyzerMonitorServiceRole",
  "startTime": "2026-10-01T00:00:00Z",
  "trails": [
    { "cloudTrailArn": "arn:aws:cloudtrail:eu-west-2:123456789012:trail/management-events", "allRegions": true }
  ]
}
JSON
JOB_ID=$(aws accessanalyzer start-policy-generation \
  --policy-generation-details "principalArn=arn:aws:iam::${ACCOUNT_ID}:role/<the-broad-role>" \
  --cloud-trail-details file://trail.json \
  --query jobId --output text)
aws accessanalyzer get-generated-policy --job-id "$JOB_ID" --include-resource-placeholders \
  --query '[jobDetails.status, generatedPolicyResult.generatedPolicies[].policy]'

The job takes a few minutes. When the status is SUCCEEDED, the draft lists the actions the role used, with placeholders such as arn:aws:s3:::${BucketName} where you should put real ARNs. Treat it as a draft, not an answer:

  • S3 object calls do not appear as actions. Access Analyzer does not identify actions from data events, and GetObject and PutObject are data events. For an app like this one, the draft says that S3 was used, and you add the object actions and the prefix yourself, exactly as you did in this tutorial.
  • Rare paths are missing. A monthly report or an error handler that did not run in the date range is not in the logs. Check the code for every AWS call before you swap policies.
  • Swap in stages. Add the tightened policy next to the broad one, remove the broad one, then watch the app's logs for AccessDenied for a few days. A permissions boundary like the one above is a good safety net while you do this.

/tutorials/test-iam-policies-before-you-attach-them shows how to check a tightened policy with the policy simulator before it goes live.

Check it worked

aws accessanalyzer list-policy-generations --query 'policyGenerations[].[principalArn,status]' --output text shows your role with SUCCEEDED. You have a written list of the actions in the draft, plus any you added by hand, and each one maps to something the app's code does.

Step 8 · Clean up

Remove things in the order AWS requires: the profile comes off the instance before the role can leave the profile, and the role must be gone before its boundary policy can be deleted. The bucket and every name below are the demo's own; check that before you run the recursive delete.

On your laptop:

Bash
cd ~/iam-app-demo
ASSOC_ID=$(aws ec2 describe-iam-instance-profile-associations \
  --filters Name=instance-id,Values="$INSTANCE_ID" \
  --query 'IamInstanceProfileAssociations[0].AssociationId' --output text)
aws ec2 disassociate-iam-instance-profile --association-id "$ASSOC_ID"
aws iam remove-role-from-instance-profile --instance-profile-name iam-app-demo-profile \
  --role-name iam-app-demo-role
aws iam delete-instance-profile --instance-profile-name iam-app-demo-profile
aws iam delete-role-policy --role-name iam-app-demo-role --policy-name uploads-access
aws iam delete-role --role-name iam-app-demo-role
aws iam delete-policy --policy-arn "$BOUNDARY_ARN"
aws s3 rm "s3://${BUCKET}" --recursive
aws s3 rb "s3://${BUCKET}"
cd ~
rm -rf ~/iam-app-demo

On the instance, delete the test files with rm -f hello.txt downloaded.txt. If you launched the instance only for this tutorial, terminate it as shown in /tutorials/launch-an-ec2-instance-and-connect, because it bills until you do.

Check it worked

aws iam get-role --role-name iam-app-demo-role and aws iam get-instance-profile --instance-profile-name iam-app-demo-profile both fail with NoSuchEntity, aws s3 ls "s3://${BUCKET}" fails with NoSuchBucket, and ~/iam-app-demo is gone.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.