IAM explained by writing policies: users, roles, trust policies and least privilege
Learn AWS IAM by writing real policies: reading a statement line by line, roles and trust policies, assuming a role from the CLI, testing with the policy simulator and trimming access with IAM Access Analyzer.
IAM is the AWS service everyone uses and few people enjoy. Most of us learn it by pasting "Action": "*" until the error goes away. It's the easy way out. The fix is not to read the whole IAM user guide. It's to write a few policies by hand and see exactly what each line does.
In this blog we will write policies for a small app, give it a role, write the trust policy that says who may use that role, assume a role from the CLI, and then check and trim it with the policy simulator and IAM Access Analyzer. It's a beginner post, but you should have an account set up as in setting up a new AWS account safely and the AWS CLI v2. Everything uses placeholders (account 111122223333, example.com).
Users, groups and roles in two minutes
A user is a long lived identity, usually with a password or access keys. A group is a bag of users that share policies. A role has no password and no keys. Something assumes it and gets temporary credentials for an hour or so. That something can be a person, an EC2 instance, an ECS task, a Lambda function or another account.
For people, use IAM Identity Center, which hands out roles behind the scenes. For code running on AWS, use roles. IAM users are left for the few cases that really need a static key. I have one of those: the SMTP login Ghost uses to send email through SES. SES SMTP passwords are derived from an IAM access key, so there's no way around a user there. That user can do exactly one thing, ses:SendRawEmail, with a condition that the From address is on my domain.
Reading a policy line by line
Let us start with the policy everyone has written once.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:*", "ssm:*"],
"Resource": "*"
}
]
}
Version is always 2012-10-17. It's the policy language version and you never change it. Statement is a list. Each statement has an Effect (Allow or Deny), the Actions it covers, the Resources they apply to, and optionally a Condition.
How bad is that one? I ran it through parliament, an offline IAM linter, to see. It expanded s3:* and ssm:* on * to 232 actions (145 for S3, 87 for SSM), including s3:DeleteBucket, s3:PutBucketPolicy and ssm:SendCommand. That last one runs shell commands on your instances. For an app that reads one config value, that's a lot.
A least privilege policy for shorty
shorty is the URL shortener this tutorial series builds (the Go code starts in building a REST API in Go with only the standard library). Say it gets two new needs on AWS: read its config from SSM Parameter Store under /shorty/, and write a monthly CSV export of links into one S3 prefix. Here is the policy I wrote for that.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadWriteLinkExports",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::example-shorty-exports/links/*"
},
{
"Sid": "ListOnlyTheLinksPrefix",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::example-shorty-exports",
"Condition": {
"StringLike": {
"s3:prefix": ["links/", "links/*"]
}
}
},
{
"Sid": "ReadOwnConfig",
"Effect": "Allow",
"Action": ["ssm:GetParameter", "ssm:GetParametersByPath"],
"Resource": [
"arn:aws:ssm:ap-south-1:111122223333:parameter/shorty",
"arn:aws:ssm:ap-south-1:111122223333:parameter/shorty/*"
]
},
{
"Sid": "DecryptSecureStringsViaSsmOnly",
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "arn:aws:kms:ap-south-1:111122223333:key/11111111-2222-3333-4444-555555555555",
"Condition": {
"StringEquals": {
"kms:ViaService": "ssm.ap-south-1.amazonaws.com"
}
}
}
]
}
There are a few things in there that trip people up.
s3:GetObjectworks on objects, so its resource ends in/*.s3:ListBucketworks on the bucket, so its resource has no/*. Mix them up and you get AccessDenied with a perfectly correct looking policy. This one catches a lot of people.- The
s3:prefixcondition stops the app listing the rest of the bucket. GetParametersByPathon/shortyneeds the path itself as a resource as well as/shorty/*.- SecureString parameters are encrypted with KMS. If you use your own key, the app needs
kms:Decrypt, andkms:ViaServicesays "only when SSM is asking on my behalf". With the defaultaws/ssmkey you can leave that statement out.
The Sid is just a label. I always add one, it makes the simulator output and CloudTrail errors easier to match up.
Deny wins
On top of that I added a small inline policy with an explicit deny.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "NeverDeleteExports",
"Effect": "Deny",
"Action": ["s3:DeleteObject", "s3:DeleteObjectVersion", "s3:DeleteBucket"],
"Resource": [
"arn:aws:s3:::example-shorty-exports",
"arn:aws:s3:::example-shorty-exports/*"
]
}
]
}
The rule is short. Everything starts as denied. An Allow anywhere makes it allowed. An explicit Deny anywhere beats every Allow. So even if someone later attaches a broad policy to this role, the exports can't be deleted through it. Nothing above allows delete anyway, but the deny is basically a guard rail for the future.
Roles and trust policies
A role has two policies and they answer different questions. The permissions policy (what we wrote above) says what the role can do. The trust policy says who can become the role. Here's the trust policy for shorty running as an ECS task.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ecs-tasks.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"aws:SourceAccount": "111122223333"
},
"ArnLike": {
"aws:SourceArn": "arn:aws:ecs:ap-south-1:111122223333:*"
}
}
}
]
}
Notice there's no Resource. The trust policy is attached to the role, so the role is the resource. The conditions make sure only ECS in my account can use it, which protects against the confused deputy problem. My blog's host has the same shape with ec2.amazonaws.com as the principal. That instance role has the AWS managed policy for SSM (so I can use SSM instead of SSH) and one inline policy that can only get and put objects in the backup bucket.
Creating the role and attaching both policies looks like this.
aws iam create-role \
--role-name shorty-app \
--assume-role-policy-document file://policies/trust-ecs-tasks.json
aws iam create-policy \
--policy-name shorty-app \
--policy-document file://policies/shorty-app.json
aws iam attach-role-policy \
--role-name shorty-app \
--policy-arn arn:aws:iam::111122223333:policy/shorty-app
aws iam put-role-policy \
--role-name shorty-app \
--policy-name never-delete-exports \
--policy-document file://policies/deny-delete.json
Assuming a role from the CLI
Roles for people work the same way. I'd make a shorty-debug role with the same permissions, so you can poke at things as the app would see them. The trust policy trusts the account, and the condition narrows it to the admin role that Identity Center creates for you.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OnlyIdentityCenterAdmins",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:root" },
"Action": "sts:AssumeRole",
"Condition": {
"ArnLike": {
"aws:PrincipalArn": "arn:aws:iam::111122223333:role/aws-reserved/sso.amazonaws.com/*/AWSReservedSSO_AdministratorAccess_*"
}
}
}
]
}
arn:aws:iam::111122223333:root here means "the account". It doesn't mean the root user. See, that one confuses everybody the first time.
I first wrote this with an aws:MultiFactorAuthPresent condition, which is the usual example. Then I realised it doesn't fit an Identity Center login. Now what happens is, that condition checks MFA on the call to AssumeRole, which works for an IAM user who passes --serial-number and --token-code. An Identity Center user does MFA at the portal, so I went with the principal ARN instead. The MFA version is still in my code folder for anyone on IAM users.
The simplest way to use the role is a profile in ~/.aws/config.
[profile shorty-debug]
role_arn = arn:aws:iam::111122223333:role/shorty-debug
source_profile = admin
role_session_name = me-debugging
region = ap-south-1
aws sts get-caller-identity --profile shorty-debug
The CLI calls sts:AssumeRole for you and caches the temporary keys. The ARN printed will be an assumed-role/shorty-debug/me-debugging one. You can also call aws sts assume-role directly and export the three values it returns, but the profile is less typing.
Testing with the policy simulator
Before deploying I'd rather know answer than find out from a 403. The simulator evaluates the role's real policies without doing anything.
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::111122223333:role/shorty-app \
--action-names s3:GetObject s3:PutObject s3:DeleteObject \
--resource-arns arn:aws:s3:::example-shorty-exports/links/2026-11.csv \
--query 'EvaluationResults[].[EvalActionName,EvalDecision]' \
--output table
You'd expect allowed for get and put and explicitDeny for delete. implicitDeny means nothing allowed it, explicitDeny means a Deny statement matched. That difference tells you where to look. There's also simulate-custom-policy, which takes a policy file instead of an existing role, handy while you're still writing it. It only looks at a bucket policy if you pass one with --resource-policy, so keep that in mind for S3.
Trimming with IAM Access Analyzer
Access Analyzer does three things that help here. First, validate-policy checks grammar and gives suggestions, a lot like a linter.
aws accessanalyzer validate-policy \
--policy-type IDENTITY_POLICY \
--policy-document file://policies/shorty-app.json
Second, an unused access analyzer lists roles, keys and permissions nobody has used in N days. It's a paid feature (priced per role and user analysed each month), so check the pricing page first.
aws accessanalyzer create-analyzer \
--analyzer-name unused-access \
--type ACCOUNT_UNUSED_ACCESS \
--configuration '{"unusedAccess": {"unusedAccessAge": 90}}'
Third, it can generate a policy from what a role actually did, by reading your CloudTrail trail (start-policy-generation, then get-generated-policy). Its limit is CloudTrail itself: with only management events, S3 object reads and writes aren't logged, so they won't be in the generated policy. Use it as a starting point and review it.
What I checked, and how
I didn't run any of this against a live account. I checked every policy with python's json module, linted them with parliament 1.6.4 and checked every CLI command and its JSON inputs against the AWS CLI's service models offline. parliament flagged all four trust policies as "MALFORMED, Statement contains neither Resource nor NotResource". That's expected, a trust policy has no Resource, so the linter just doesn't know it's looking at one. The shorty policy came back with zero findings.
That's it. Next time you're tempted to write "Resource": "*", write the ARN out, it takes a minute.