IAM policies in depth: conditions, variables and boundaries

Managed policies like ReadOnlyAccess get you started, but real jobs need rules of your own, like “only in Mumbai”, “only your own files” or “only servers tagged with your name”. These IAM policy examples show you how to write rules like that in JSON and, just as much, how to test them before anyone relies on them.

You’ll write a Region guard, a per-user rule with a policy variable, a tag-based rule and a permission boundary, and check each of them with IAM Access Analyzer and the policy simulator. None of this lab costs anything.

TimeYou needBy the end you can
60 minutesYour laptop signed in with aws login --profile saat-admin (Lesson 6).Read and write policy statements with conditions, use policy variables and tags, set a permission boundary, and catch the silent mistakes with Access Analyzer and the simulator.

What it is, in one line

IAM policy examples are JSON rules made of Effect, Action, Resource and Condition, which you test before you attach them.

In Simple Words

Rules for borrowing the family car

“You can use the car” is a policy. “You can use the car, but only in our city” adds a condition, and “you can only drive the car whose key tag has your name on it” uses a tag. Parents might add “whatever your older brother lets you do, you still can’t take it on the highway”, which is a permission boundary, a ceiling nobody can lift. And a sensible parent checks that the rules make sense before handing over the keys, which is what the simulator does.

Engineer's View

The grammar of a policy

A policy has a Version (always 2012-10-17) and one or more Statement blocks. Each statement has Effect, Action (or NotAction), Resource (or NotResource) and an optional Condition.

Conditions are built from operators such as StringEquals, StringLike, IpAddress, Bool and DateLessThan, used with keys such as aws:RequestedRegion, aws:MultiFactorAuthPresent, aws:SourceIp, aws:PrincipalTag/team and ec2:ResourceTag/owner. Rules based on tags are called attribute-based access control (ABAC), where you write one policy and the tags decide who gets what.

Policy variables like ${aws:username} get filled in at request time, but only when Version is 2012-10-17. Leave that out and the text is taken literally, so the rule silently never matches.

A permission boundary is a managed policy attached to a user or role as a limit. The effective permission is whatever the identity policy and the boundary both allow, which means you can safely hand out “create roles for your app”, since nothing that gets created can go past the boundary.

IAM doesn’t check whether action names exist when you save a policy, so ssm:PutParamter saves without complaint and grants nothing. aws accessanalyzer validate-policy catches that, and the simulator shows you the outcome for a particular request.

How it works, step by step

Every policy you write goes round the same loop.

1Write it small

Begin with the job (“Priya must restart her own servers in Mumbai”) and write down the exact actions, resources and conditions. Keep * out of actions unless you really mean it.

IAM policy examples: the five parts of a policy statement

2Validate it

Run Access Analyzer’s checks, fix every ERROR and read every SECURITY_WARNING. It catches typos, missing versions and grants that are wider than you intended.

3Simulate it

Put the questions you care about to the simulator: is it allowed in Mumbai, denied in Virginia, denied for somebody else’s server? Give it the context values (Region, tags, user name) that the conditions look at.

4Attach, watch, shrink

Attach it to a group or role rather than a person, and after a few weeks check the last-accessed data and take out whatever isn’t used.

When you’re reading someone else’s policy, run the same five-part check in the same order.

IAM policy examples: Access Analyzer, policy simulator, boundaries and last accessed

The tools below turn all this from guesswork into a routine, and teams that use them before every change rarely hear “it worked in test but not for the user”.

✅ Checkpoint: You can name the five parts of a statement and say what a permission boundary does and doesn’t do.

Hands-on lab: IAM policy examples you test before use

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

From now on, start every lab like this:

cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$acct = aws sts get-caller-identity --query Account --output text

All the policy files use single-quoted here-strings (@' … '@). In a double-quoted one, PowerShell would read ${aws:username} as one of its own variables and quietly strip it out.

1A Region guard: deny everything outside Mumbai

Paste this whole block:

@'
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "ec2:*", "Resource": "*" }] }
'@ | Set-Content allow-ec2.json

@'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "OnlyMumbai",
    "Effect": "Deny",
    "NotAction": ["iam:*", "sts:*", "organizations:*", "budgets:*", "ce:*", "support:*",
                  "cloudfront:*", "route53:*", "health:*", "account:*", "signin:*"],
    "Resource": "*",
    "Condition": { "StringNotEquals": { "aws:RequestedRegion": ["ap-south-1"] } }
  }]
}
'@ | Set-Content region-guard.json

NotAction lists the global services that don’t run in a Region, so the guard leaves sign-in, IAM and billing working.

2Validate and simulate the guard

Run this:

aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://region-guard.json --query "findings[].[findingType,issueCode]" --output text

foreach ($r in 'ap-south-1','us-east-1') {
  aws iam simulate-custom-policy --policy-input-list file://allow-ec2.json file://region-guard.json --action-names ec2:RunInstances --context-entries "ContextKeyName=aws:RequestedRegion,ContextKeyValues=$r,ContextKeyType=string" --query "EvaluationResults[].EvalDecision" --output text
}

You should see this (Access Analyzer might print a SUGGESTION line, or nothing at all):

allowed
explicitDeny

3Your own corner with a policy variable

Paste this whole block:

@'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ssm:PutParameter", "ssm:GetParameter"],
    "Resource": "arn:aws:ssm:ap-south-1:ACCOUNT_ID:parameter/lab/${aws:username}/*"
  }]
}
'@ -replace 'ACCOUNT_ID', $acct | Set-Content my-params.json

$myParam = "arn:aws:ssm:ap-south-1:$($acct):parameter/lab/yourname.admin/note"
$other = "arn:aws:ssm:ap-south-1:$($acct):parameter/lab/priya.dev/note"
foreach ($res in $myParam, $other) {
  aws iam simulate-custom-policy --policy-input-list file://my-params.json --action-names ssm:PutParameter --resource-arns $res --context-entries "ContextKeyName=aws:username,ContextKeyValues=yourname.admin,ContextKeyType=string" --query "EvaluationResults[].EvalDecision" --output text
}

You should see this:

allowed
implicitDeny

It’s one policy attached to a whole group, and each person can only write under their own name.

4Tag-based access: only your own servers

Paste this whole block:

@'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ec2:StartInstances", "ec2:StopInstances"],
    "Resource": "arn:aws:ec2:ap-south-1:*:instance/*",
    "Condition": { "StringEquals": { "ec2:ResourceTag/owner": "${aws:username}" } }
  }]
}
'@ | Set-Content owner-tag.json

$inst = "arn:aws:ec2:ap-south-1:$($acct):instance/i-0123456789abcdef0"
foreach ($owner in 'yourname.admin','priya.dev') {
  aws iam simulate-custom-policy --policy-input-list file://owner-tag.json --action-names ec2:StopInstances --resource-arns $inst --context-entries "ContextKeyName=aws:username,ContextKeyValues=yourname.admin,ContextKeyType=string" "ContextKeyName=ec2:ResourceTag/owner,ContextKeyValues=$owner,ContextKeyType=string" --query "EvaluationResults[].EvalDecision" --output text
}

You should see this:

allowed
implicitDeny
IAM policy examples lab: Region guard and permission boundary in the simulator
Simulator results. Decisions like these will match exactly, though your account number will be different.

5A permission boundary: admin, but only up to a ceiling

Paste this whole block:

@'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ssm:*", "ec2:Describe*", "s3:Get*", "s3:List*"],
    "Resource": "*"
  }]
}
'@ | Set-Content boundary.json

$bArn = aws iam create-policy --policy-name lab-boundary --policy-document file://boundary.json --query Policy.Arn --output text
$devArn = aws iam create-user --user-name lab-dev --permissions-boundary $bArn --tags Key=course,Value=saatvedha-aws Key=lesson,Value=07 --query User.Arn --output text
aws iam attach-user-policy --user-name lab-dev --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
aws iam simulate-principal-policy --policy-source-arn $devArn --action-names ec2:TerminateInstances ssm:GetParameter --query "EvaluationResults[].[EvalActionName,EvalDecision]" --output text

You should see this:

ec2:TerminateInstances  implicitDeny
ssm:GetParameter        allowed

lab-dev has AdministratorAccess and still can’t terminate an instance, because the boundary doesn’t allow it. The boundary grants nothing by itself, so if you took away AdministratorAccess, ssm:GetParameter would be denied as well.

✅ Checkpoint: The guard returns allowed for Mumbai and explicitDeny for us-east-1, the variable and tag rules only allow your own items, and the boundary blocks terminate. Hang on to the files for the break lab.

Break It, Then Fix It

The two most dangerous policy mistakes are ones IAM accepts without a word.

1Break it: a typo in an action name

Make a policy with one letter missing and validate it:

@'
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "ssm:PutParamter", "Resource": "*" }] }
'@ | Set-Content typo.json
aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://typo.json --query "findings[].[findingType,issueCode]" --output text

You’ll get this finding:

ERROR   INVALID_ACTION

IAM would have saved this policy happily, and the user would have got “Access Denied” without any idea why. The full finding message even suggests the right action. Fix: change it to ssm:PutParameter and keep validating until there’s no ERROR.

2Break it: forget the Version line

Copy my-params.json without its Version line, then validate and simulate it:

(Get-Content my-params.json) | Where-Object { $_ -notmatch '"Version"' } | Set-Content no-version.json
aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://no-version.json --query "findings[?findingType=='ERROR'].issueCode" --output text
aws iam simulate-custom-policy --policy-input-list file://no-version.json --action-names ssm:PutParameter --resource-arns $myParam --context-entries "ContextKeyName=aws:username,ContextKeyValues=yourname.admin,ContextKeyType=string" --query "EvaluationResults[].EvalDecision" --output text

You should see this:

VARIABLE_UNSUPPORTED_IN_VERSION
implicitDeny
IAM policy examples break lab: invalid action and a missing Version
Both silent mistakes caught. Apart from your file paths, this output will match exactly.

With no Version, ${aws:username} is read as plain text, so the resource never matches and your own write gets denied. Fix: always begin with "Version": "2012-10-17".

3Clean up

Paste this whole block:

aws iam detach-user-policy --user-name lab-dev --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
aws iam delete-user --user-name lab-dev
aws iam delete-policy --policy-arn $bArn
Remove-Item allow-ec2.json, region-guard.json, my-params.json, owner-tag.json, boundary.json, typo.json, no-version.json

✅ Checkpoint: Access Analyzer caught both silent mistakes, you fixed them, and lab-dev and lab-boundary have been removed.

This happened at work

“Power users” who switched off the audit log

A product company wanted its developers to have “everything except IAM”, and someone wrote a single statement for it: Allow with NotAction: iam:* on *. It looked neat and it worked fine for months.

Then a developer trying to save money in a test account spotted the CloudTrail and GuardDuty charges and switched both off. The policy let him, because “everything except IAM” includes the security services. A few weeks later there was an incident in that account and nobody could investigate it, because nothing had been logged.

The team threw out the home-made policy and used PowerUserAccess with explicit Deny statements for cloudtrail:StopLogging, cloudtrail:DeleteTrail, guardduty:DeleteDetector and changes to AWS Config. Later they moved those denies into a service control policy so no account admin could undo them, and now every new policy goes through Access Analyzer validation in the pull request.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
Typo in an action nameIt saves without an error and grants nothingRun aws accessanalyzer validate-policy before saving
Missing VersionPolicy variables turn into plain text and never matchAlways include “Version”: “2012-10-17”
Double-quoted PowerShell here-string with ${aws:username}PowerShell removes the variable textUse single-quoted here-strings and -replace for your own values
Allow + NotActionGrants far more than you’d expect (every other service)Use NotAction mostly with Deny, and prefer explicit Allow lists
A Region guard with no exceptions for global servicesIAM, billing and sign-in breakList global services in NotAction, as in the lab
Expecting a boundary to grant accessStill deniedA boundary only limits, so the identity policy has to allow it too

Interview questions

Click a question to open it. Each one is worded the way an interviewer might ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. If I showed you an IAM policy, what parts would you expect to see in each statement?

Why they ask this: They’re checking that you can read policy grammar, because you can’t debug a policy you can’t read.

How you might answer: Each statement has an Effect, either Allow or Deny, then Action, Resource and an optional Condition. Resource-based policies and trust policies also carry a Principal, saying who the statement applies to.

2. Your manager says, “Nobody should create anything outside Mumbai.” How would you enforce that?

Why they ask this: They want to see how you handle a very common real requirement, and whether you remember that global services need an exception.

How you might answer: I’d write a Deny statement using StringNotEquals on aws:RequestedRegion, with NotAction leaving out global services like IAM, STS and billing. In an organization I’d put it into a service control policy so account admins can’t take it off.

3. Can you explain in simple words what a policy variable is and why it’s useful?

Why they ask this: They want to see if you can write one policy that works for lots of people, which shows you think about reuse rather than copying policies around.

How you might answer: A policy variable is a placeholder like ${aws:username} that AWS fills in at the moment the request happens, so a single policy can say “your own folder” for everyone. It only works when the policy uses Version 2012-10-17.

2–5 years experience

4. Developers want to create their own IAM roles for their apps. How would you allow that without giving away the keys to the account?

Why they ask this: They want to see you can delegate safely with permission boundaries. Saying no to everything slows teams down, and saying yes to everything is a risk.

How you might answer: I’d use a permission boundary, a managed policy that sets the most a user or role can ever be allowed. Developers can create roles, but only if they attach our boundary, so none of the roles they make can go past it.

5. You write a new policy and the user says it “doesn’t work”. How do you debug it?

Why they ask this: They’re looking for a methodical way to debug policies, because guessing and piling on more permissions is the habit they want to steer clear of.

How you might answer: I’d validate it with Access Analyzer first to catch typos and version problems, and then run the policy simulator with the user, action, resource and context values. I’d also read the exact AccessDenied message to see which policy type denied it, and check for SCPs, boundaries and resource policies.

6. How would you explain ABAC to a new team member, and why would you choose it?

Why they ask this: They want to know you’re aware of modern access patterns, and ABAC starts to matter when the number of people and resources keeps growing.

How you might answer: I’d tell them ABAC stands for attribute-based access control, where permissions depend on tags. A user might be able to run StopInstances only when the instance’s owner tag matches their own, for example. It scales nicely, because new people and resources only need the right tags instead of new policies.

Senior level

7. You find a policy that uses Allow with NotAction. Why might that worry you, and when is NotAction the right choice?

Why they ask this: They want to see a deep grasp of policy logic, since this mistake can quietly grant far more than anyone intended.

How you might answer: Allow with NotAction grants every action that isn’t on the list, in every current and future service, security ones included, so it can give away far more than anyone meant. NotAction is safest inside Deny statements, for example “deny everything outside this Region, except these global services”.

8. How would you build policy quality checks into your team’s daily workflow?

Why they ask this: They want to see you think in terms of automation and governance instead of one-off reviews, because senior engineers are expected to make good practice the default.

How you might answer: Our policies live in code, in CloudFormation, CDK or Terraform. On every pull request the pipeline runs Access Analyzer validate-policy plus our own checks, like “no new public access”, and fails if there are errors or security warnings. Then every quarter we go through Access Advisor data and remove permissions nobody uses.

Quick quiz

Q1. IAM accepts a policy with the action “ssm:PutParamter”. What happens when the user tries to put a parameter?

  1. It works
  2. It is denied, because the action name matches nothing
  3. IAM fixes the typo
  4. The policy is rejected when saved
Show answer

B: IAM doesn’t check action names when you save, but Access Analyzer validation catches it.

Q2. What happens to ${aws:username} if the policy has no Version element?

  1. It still works
  2. It is used as plain text
  3. It becomes *
  4. The policy fails to save
Show answer

B: variables need Version 2012-10-17, and without it they’re treated as literal text.

Q3. A user has AdministratorAccess and a boundary that allows only ssm:*. Can they terminate an EC2 instance?

  1. Yes
  2. No
  3. Only in Mumbai
  4. Only with MFA
Show answer

B: the effective permissions are only what the identity policy and the boundary both allow.

Q4. Which condition key limits actions to certain Regions?

  1. aws:SourceIp
  2. aws:RequestedRegion
  3. aws:CurrentTime
  4. ec2:Region
Show answer

B: aws:RequestedRegion is the Region the request gets sent to.

Q5. Why should a Region guard exclude IAM, STS and billing actions?

  1. They are cheap
  2. They are global services, not tied to your Region
  3. They can’t be denied
  4. They need MFA
Show answer

B: otherwise the global services get blocked, and sign-in and administration break.

Quick recap

  • Read every statement as Effect, Action, Resource, Condition (and Principal for resource policies).
  • Conditions and tags let a single policy cover lots of cases, such as Regions, MFA and owner tags.
  • Policy variables need Version 2012-10-17, and in PowerShell you should use single-quoted here-strings.
  • A permission boundary puts a cap on permissions and grants nothing on its own.
  • Before you attach a policy, validate it with Access Analyzer and test it with the simulator.

Next lesson

Lesson 8: VPC basics: CIDR, subnets and route tables → Next you’ll build saat-vpc, the network that every later lesson runs on.

Further reading: IAM policy examples

If you want to go further with IAM policy examples, AWS keeps a long list of Example IAM identity-based policies, and the checks you ran are documented in the IAM Access Analyzer policy check reference. The full plan for this course is on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.