Cloud and deployment · Intermediate · 18 min
Test AWS IAM policies before you attach them with the policy simulator and Access Analyzer
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4
You will validate an IAM policy with Access Analyzer, fix its findings, prove what it allows and denies with the IAM policy simulator, including a Condition, and finish with a script that runs both checks on a folder of policies in CI.
On this page
An IAM policy is easy to write and hard to read correctly. A typo in an action name fails silently, a statement with no Resource is rejected only when you try to save it, and "Resource": "*" on the wrong action hands out far more than you meant. The usual way people find out is in production: the deploy fails with AccessDenied, or a security review finds a role that can do almost anything.
AWS gives you two free tools to catch these problems before a policy is attached to anything. IAM Access Analyzer policy validation reads a policy and reports errors, security warnings, warnings and suggestions, each with an issue code. The IAM policy simulator answers a narrower question: given these policies, is this action on this resource allowed, and which statement decided it? One checks how the policy is written; the other checks what it does. You want both.
In this tutorial you take a draft policy for a deploy job (upload release files to one S3 prefix and pass one role to Amazon ECS), validate it, fix what Access Analyzer finds, simulate the actions it should and should not allow, including a Condition that needs a context key, simulate a real role, and then wrap the checks in a script that a CI job can run on every pull request.
Policy validation is provided at no additional charge, and IAM itself has no charge (both checked on AWS's pricing pages on 26 November 2026). Access Analyzer's custom policy checks, such as check-no-new-access, are billed per call and are not used here. The S3 bucket and the ECS task role in the policy do not need to exist: the simulator evaluates ARNs without looking them up. The only thing you create is one IAM role, which you delete at the end.
Everything lives in ~/iam-policy-tests-demo, and the role is named iam-test-demo-deployer, so nothing collides with what your account already has.
Step 1 · Set up a working folder and check who you are
Point the CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder). Access Analyzer is a regional service, so make sure a Region is set too, either in the profile or with AWS_REGION. IAM is global, so the simulator works the same in any Region.
aws --version
aws sts get-caller-identity --query Arn --output text
aws configure listNow make the working folder and save the values the policies use. ACCOUNT_ID comes from your own account, and BUCKET is a name for the release bucket. Change it to your real bucket name if you have one; any valid name works for the checks.
mkdir -p ~/iam-policy-tests-demo/policies ~/iam-policy-tests-demo/trust
cd ~/iam-policy-tests-demo
export ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"
export BUCKET="iam-test-demo-releases-${ACCOUNT_ID}"
export TASK_ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/iam-test-demo-task-role"
echo "$ACCOUNT_ID $BUCKET"The later steps use these three variables. If you open a new terminal, run the three export lines again from inside ~/iam-policy-tests-demo.
Check it worked
aws --version starts with aws-cli/2.42, get-caller-identity prints an ARN from your sandbox account, the region row of aws configure list shows a Region name rather than <not set> (its TYPE column says whether it came from env or the config file; if it says <not set>, run export AWS_REGION=<your-region>), and the last command prints a 12-digit account ID followed by iam-test-demo-releases- and the same digits.
Step 2 · Validate a draft policy with Access Analyzer
Here is the first draft of the deploy policy, the kind of thing that gets written in a hurry. It has three problems. Read it and see whether you can spot them before Access Analyzer does.
cat > policies/deploy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadReleases",
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObjects"]
},
{
"Sid": "PassTaskRole",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "*"
}
]
}
EOF
jq empty policies/deploy.json && echo "valid JSON"jq empty only proves the file is well-formed JSON. It knows nothing about IAM. Ask Access Analyzer instead. --policy-type IDENTITY_POLICY says this policy will be attached to a user, group or role:
aws accessanalyzer validate-policy \
--policy-type IDENTITY_POLICY \
--policy-document file://policies/deploy.json \
--query 'findings[].[findingType,issueCode]' \
--output textYou should see something like this (the order can differ):
ERROR INVALID_ACTION
ERROR MISSING_RESOURCE
SECURITY_WARNING PASS_ROLE_WITH_STAR_IN_RESOURCEEach finding has a type, an issue code, a sentence of explanation (findingDetails), a learnMoreLink, and a locations list that points at the exact line and column. Drop the --query and --output options to see all of it. The four types mean:
- ERROR: part of the policy does not work. IAM may refuse to save it, or a statement may never match.
- SECURITY_WARNING: the policy works but allows more than is usually safe.
- WARNING: it works but does not follow good practice, for example a missing
Version. - SUGGESTION: a tidy-up that does not change access, such as a redundant action.
Here, s3:GetObjects is not a real action (the real one is s3:GetObject), the first statement has no Resource, and iam:PassRole on * would let whoever holds this policy hand any role in the account to any AWS service that accepts one. That last one is how a deploy job quietly becomes an administrator: it passes an admin role to a service it controls.
Check it worked
The command prints at least one ERROR line and one SECURITY_WARNING line naming PASS_ROLE_WITH_STAR_IN_RESOURCE. If you remove --query and --output, the INVALID_ACTION finding's findingDetails suggests the action name you probably meant.
Step 3 · Fix the findings and validate again
Rewrite the policy with each finding fixed:
- the action is
s3:GetObject, - the S3 statement names object ARNs under one prefix (
releases/), not the whole bucket, iam:PassRolenames the one task role and, through theiam:PassedToServicecondition key, only lets it be passed to ECS tasks.
The heredoc delimiter is unquoted this time, so the shell fills in ${BUCKET} and ${TASK_ROLE_ARN}:
cat > policies/deploy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadReleases",
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject"],
"Resource": "arn:aws:s3:::${BUCKET}/releases/*"
},
{
"Sid": "PassTaskRoleToEcsOnly",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "${TASK_ROLE_ARN}",
"Condition": {
"StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" }
}
}
]
}
EOF
jq empty policies/deploy.json && grep -c "$ACCOUNT_ID" policies/deploy.jsonValidate it again, and this time ask only for the number of findings:
aws accessanalyzer validate-policy \
--policy-type IDENTITY_POLICY \
--policy-document file://policies/deploy.json \
--query 'length(findings)'A policy with no findings is not the same as a correct policy. Access Analyzer checks grammar and known risky patterns. It cannot know that your deploy job should never delete releases. That is what the simulator is for.
Check it worked
grep -c prints a number of at least 1 (the account ID was filled in), and validate-policy prints 0. If it prints a higher number, run it without --query and read the findingDetails; a typo in the bucket or role ARN is the usual cause.
Step 4 · Simulate the actions the policy should and should not allow
aws iam simulate-custom-policy takes one or more policy documents, a list of actions and a list of resource ARNs, and returns a decision for each action: allowed, implicitDeny (nothing allowed it) or explicitDeny (a Deny statement matched). It does not call S3 or IAM for real, and action names cannot contain wildcards, so you test the exact API calls your job makes.
Define a small helper so each test is one line. It works in bash and zsh:
sim() {
aws iam simulate-custom-policy \
--policy-input-list file://policies/deploy.json \
--action-names "$1" \
--resource-arns "$2" \
"${@:3}" \
--query 'EvaluationResults[0].EvalDecision' \
--output text
}Now write down what you expect, then ask:
sim s3:PutObject "arn:aws:s3:::${BUCKET}/releases/app-1.4.0.zip"
sim s3:PutObject "arn:aws:s3:::${BUCKET}/secrets/db.env"
sim s3:DeleteObject "arn:aws:s3:::${BUCKET}/releases/app-1.4.0.zip"The first should be allowed. The second and third should be implicitDeny: the policy only covers releases/, and it never grants s3:DeleteObject.
Test the Condition with a context key
The PassRole statement only applies when iam:PassedToService equals ecs-tasks.amazonaws.com. In a real request AWS fills that value in. In a simulation you supply it. First, ask IAM which context keys the policy uses:
aws iam get-context-keys-for-custom-policy \
--policy-input-list file://policies/deploy.json \
--query 'ContextKeyNames' --output textThat prints iam:PassedToService. Simulate passing the task role to ECS, to EC2, and with no value at all:
sim iam:PassRole "$TASK_ROLE_ARN" \
--context-entries ContextKeyName=iam:PassedToService,ContextKeyValues=ecs-tasks.amazonaws.com,ContextKeyType=string
sim iam:PassRole "$TASK_ROLE_ARN" \
--context-entries ContextKeyName=iam:PassedToService,ContextKeyValues=ec2.amazonaws.com,ContextKeyType=string
sim iam:PassRole "$TASK_ROLE_ARN"
sim iam:PassRole "arn:aws:iam::${ACCOUNT_ID}:role/some-admin-role" \
--context-entries ContextKeyName=iam:PassedToService,ContextKeyValues=ecs-tasks.amazonaws.com,ContextKeyType=stringOnly the first is allowed. Passing the role to EC2 is denied by the condition, and passing a different role is denied by the Resource. When you leave the key out, the condition cannot match, so the result is implicitDeny too, and the simulator says what was missing. See it with a different query:
aws iam simulate-custom-policy \
--policy-input-list file://policies/deploy.json \
--action-names iam:PassRole \
--resource-arns "$TASK_ROLE_ARN" \
--query 'EvaluationResults[0].ResourceSpecificResults[0].MissingContextValues'When you pass specific resource ARNs, per-resource detail such as missing context values sits under ResourceSpecificResults. If a test you expect to pass comes back implicitDeny, check this list before you rewrite the policy: often the policy is right and the simulation was missing a key.
Check it worked
You have seven decisions on screen in this order: allowed, implicitDeny, implicitDeny, then allowed, implicitDeny, implicitDeny, implicitDeny. The last command prints a list containing iam:PassedToService.
Step 5 · Simulate an existing role with simulate-principal-policy
simulate-custom-policy tests documents on their own. simulate-principal-policy tests a real user, group or role with every policy attached to it, which is what you need when a role already has several policies and you are about to add one more.
Create a demo role for the deploy job. Its trust policy lets principals in your own account assume it (for a CI job you would trust your CI provider instead; see the Next steps). Validate the trust policy first: it is a resource policy, and Access Analyzer has a specific resource type for role trust policies.
cat > trust/deployer-trust.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SameAccountOnly",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::${ACCOUNT_ID}:root" },
"Action": "sts:AssumeRole"
}
]
}
EOF
aws accessanalyzer validate-policy \
--policy-type RESOURCE_POLICY \
--validate-policy-resource-type AWS::IAM::AssumeRolePolicyDocument \
--policy-document file://trust/deployer-trust.json \
--query 'findings[].[findingType,issueCode]' --output textNow create the role and attach the deploy policy as an inline policy:
aws iam create-role \
--role-name iam-test-demo-deployer \
--assume-role-policy-document file://trust/deployer-trust.json \
--query Role.Arn --output text
aws iam put-role-policy \
--role-name iam-test-demo-deployer \
--policy-name deploy \
--policy-document file://policies/deploy.json
export ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/iam-test-demo-deployer"IAM changes can take a few seconds to be visible everywhere. If the next command says the role does not exist, wait a moment and run it again.
Simulate the role. This time the policies come from IAM, not from a file:
aws iam simulate-principal-policy \
--policy-source-arn "$ROLE_ARN" \
--action-names s3:PutObject s3:DeleteObject \
--resource-arns "arn:aws:s3:::${BUCKET}/releases/app-1.4.0.zip" \
--query 'EvaluationResults[].[EvalActionName,EvalDecision]' \
--output textTry a change before you attach it
Say someone asks for the deploy job to also delete old releases. Write the extra statement as its own file and pass it with --policy-input-list. The simulator adds it to the role's real policies for this one call only; nothing is attached:
cat > policies/prune-releases.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DeleteOldReleases",
"Effect": "Allow",
"Action": "s3:DeleteObject",
"Resource": "arn:aws:s3:::${BUCKET}/releases/*"
}
]
}
EOF
aws iam simulate-principal-policy \
--policy-source-arn "$ROLE_ARN" \
--policy-input-list file://policies/prune-releases.json \
--action-names s3:DeleteObject \
--resource-arns "arn:aws:s3:::${BUCKET}/releases/app-1.0.0.zip" "arn:aws:s3:::${BUCKET}/secrets/db.env" \
--query 'EvaluationResults[0].ResourceSpecificResults[].[EvalResourceName,EvalResourceDecision]' \
--output textBe careful who can run simulate-principal-policy: it shows what another principal is allowed to do. Give it to the people and CI jobs that review policies, and give everyone else simulate-custom-policy, which only sees the documents they provide.
Know the limits of each simulator command. simulate-principal-policy uses the policies attached to the user, group or role, its permissions boundary and, if the account is in an organisation, the service control policies that apply to it. It does not fetch the bucket policy of a real bucket, and the extra resource policy you can pass in is evaluated for IAM users only, so it does not help with a role like this one. simulate-custom-policy uses only what you pass: the policy documents, an optional permissions boundary, an optional resource policy and, if you supply them, service control policies. It never looks at your own boundary or your organisation's policies. In both cases AWS states that results can differ from the live environment. Treat a simulation as a strong test, and still try the real call once in a sandbox.
Check it worked
The trust policy validation prints nothing (no findings). create-role prints the role ARN. The first simulation prints s3:PutObject with allowed and s3:DeleteObject with implicitDeny. The second prints the releases/ object as allowed and the secrets/ object as implicitDeny, and aws iam list-role-policies --role-name iam-test-demo-deployer still lists only deploy.
Step 6 · Run both checks on every policy file in a folder
Running these commands by hand does not scale past a few policies. Put the expectations next to each policy in a tests file, and let a script check them all. A tests file is a JSON list of cases: the action, the resource, an optional context list in the same shape the CLI uses, and the decision you expect.
cat > policies/deploy.tests.json <<EOF
[
{ "action": "s3:PutObject", "resource": "arn:aws:s3:::${BUCKET}/releases/app.zip", "expect": "allowed" },
{ "action": "s3:GetObject", "resource": "arn:aws:s3:::${BUCKET}/releases/app.zip", "expect": "allowed" },
{ "action": "s3:PutObject", "resource": "arn:aws:s3:::${BUCKET}/secrets/db.env", "expect": "implicitDeny" },
{ "action": "s3:DeleteObject", "resource": "arn:aws:s3:::${BUCKET}/releases/app.zip", "expect": "implicitDeny" },
{
"action": "iam:PassRole",
"resource": "${TASK_ROLE_ARN}",
"context": [
{ "ContextKeyName": "iam:PassedToService", "ContextKeyValues": ["ecs-tasks.amazonaws.com"], "ContextKeyType": "string" }
],
"expect": "allowed"
},
{
"action": "iam:PassRole",
"resource": "${TASK_ROLE_ARN}",
"context": [
{ "ContextKeyName": "iam:PassedToService", "ContextKeyValues": ["ec2.amazonaws.com"], "ContextKeyType": "string" }
],
"expect": "implicitDeny"
}
]
EOF
jq length policies/deploy.tests.jsonNow the script. For each policy file it checks the JSON, runs validate-policy and fails on any ERROR or SECURITY_WARNING, then runs every case from the matching .tests.json file through simulate-custom-policy. It builds each simulator request with jq and sends it with --cli-input-json, which avoids quoting trouble with context keys. It exits non-zero if anything fails, which is what a CI job needs.
cat > check-policies.sh <<'EOF'
#!/usr/bin/env bash
# Validate every IAM identity policy in a folder with Access Analyzer,
# then run the simulator cases in <name>.tests.json next to each policy.
set -euo pipefail
dir="${1:-policies}"
status=0
for policy in "$dir"/*.json; do
case "$policy" in *.tests.json) continue ;; esac
name="$(basename "$policy")"
if ! jq empty "$policy" 2>/dev/null; then
echo "FAIL $name: not valid JSON"
status=1
continue
fi
blocking="$(aws accessanalyzer validate-policy \
--policy-type IDENTITY_POLICY \
--policy-document "file://$policy" \
--query 'findings[?findingType==`ERROR` || findingType==`SECURITY_WARNING`].[findingType,issueCode]' \
--output text)"
if [ -n "$blocking" ]; then
echo "FAIL $name: Access Analyzer findings"
echo "$blocking"
status=1
else
echo "ok $name: no errors or security warnings"
fi
tests="${policy%.json}.tests.json"
if [ ! -f "$tests" ]; then
echo "skip $name: no $(basename "$tests")"
continue
fi
while IFS= read -r case_json; do
input="$(jq -n --rawfile doc "$policy" --argjson t "$case_json" '
{ PolicyInputList: [$doc], ActionNames: [$t.action], ResourceArns: [$t.resource] }
+ (if $t.context then { ContextEntries: $t.context } else {} end)')"
got="$(aws iam simulate-custom-policy --cli-input-json "$input" \
--query 'EvaluationResults[0].EvalDecision' --output text)"
want="$(jq -r '.expect' <<<"$case_json")"
label="$(jq -r '"\(.action) on \(.resource)"' <<<"$case_json")"
if [ "$got" = "$want" ]; then
echo "ok $name: $label is $got"
else
echo "FAIL $name: $label is $got, expected $want"
status=1
fi
done < <(jq -c '.[]' "$tests")
done
exit "$status"
EOF
chmod +x check-policies.sh
./check-policies.sh policiesprune-releases.json has no tests file, so the script validates it and prints a skip line for the simulation. That is deliberate: a policy without tests is visible in the output instead of passing quietly.
Each case is one API call, so a folder of 20 policies with 10 cases each makes about 220 calls. That is fine for a pull request check. If your team works over a slow or metered connection, as many do on prepaid mobile data, run the script in CI rather than on a laptop: the CI runner does the calls and you read one short log.
Prove the script catches a regression
A check you have never seen fail is not a check. Break the policy on purpose by widening the S3 resource to the whole bucket, run the script, then put the good version back:
cp policies/deploy.json deploy.good.json.bak
jq --arg r "arn:aws:s3:::${BUCKET}/*" '.Statement[0].Resource = $r' deploy.good.json.bak > policies/deploy.json
./check-policies.sh policies || echo "script failed as expected"
mv deploy.good.json.bak policies/deploy.json
./check-policies.sh policies && echo "all checks pass"To run this in CI, give the job a read-only role whose policy allows only access-analyzer:ValidatePolicy and iam:SimulateCustomPolicy, check the script and the policies folder into the repository, and call ./check-policies.sh policies as a step. Use short-lived credentials for the job, never stored access keys; /tutorials/deploy-to-aws-from-github-actions-with-oidc shows how for GitHub Actions. Keep the account-specific values out of the files you commit by generating them from templates in CI, or by committing the files with your real account ID if that is acceptable in your organisation.
Check it worked
The first run prints ok for deploy.json validation, six ok lines for its cases, ok for prune-releases.json and one skip line, and exits 0. With the widened resource, the line for s3:PutObject on secrets/db.env reads FAIL ... is allowed, expected implicitDeny and you see script failed as expected. After restoring the file, the last run ends with all checks pass.
Step 7 · Clean up
Delete the inline policy first: IAM will not delete a role that still has policies. Both names start with iam-test-demo-; check that before you run the commands.
aws iam delete-role-policy --role-name iam-test-demo-deployer --policy-name deploy
aws iam delete-role --role-name iam-test-demo-deployer
cd ~
rm -rf ~/iam-policy-tests-demo
unset ACCOUNT_ID BUCKET TASK_ROLE_ARN ROLE_ARNNothing else was created. The bucket, the task role and the admin role in the simulations were only ARNs.
Check it worked
aws iam get-role --role-name iam-test-demo-deployer fails with NoSuchEntity, and ls ~/iam-policy-tests-demo reports that the folder does not exist.
Next steps
- Revisit how AWS combines identity policies, resource policies, boundaries and SCPs, which is what the simulator is modelling: understand AWS IAM users, groups and roles.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials