Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 70 ยท Identity and access management

Writing IAM Policies

Read and write IAM policy JSON: Effect, Action, Resource, Condition, wildcards and variables, identity vs resource policies, managed vs inline policies, with a runnable policy evaluator.

An identity on its own can do nothing. What it may do is decided by policies: JSON documents that list allowed and denied actions on resources. Learning to read a policy quickly is one of the most valuable skills in AWS, because almost every "Access Denied" error, every security review and every least-privilege discussion comes down to a policy.

In this lesson you will take a policy apart, learn the wildcard and condition rules, and see how identity policies differ from resource policies and managed policies from inline ones. The JSON is real AWS policy syntax and is read-only here. The runnable examples are small policy evaluators written in Python for this site. They implement the core ideas (explicit deny wins, nothing allowed means denied, wildcards, a few condition operators, policy variables) but not everything real IAM supports, so they are for understanding, not for validating your real policies. For that, use the IAM policy simulator and IAM Access Analyzer in a real account.

Anatomy of a policy

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadReports",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::acme-reports",
        "arn:aws:s3:::acme-reports/*"
      ],
      "Condition": {
        "Bool": { "aws:MultiFactorAuthPresent": "true" }
      }
    }
  ]
}
  • Version is almost always "2012-10-17". It is the policy language version, not a date you update. Use it, because the older version lacks features such as policy variables.
  • Statement holds one object or a list of objects; each statement is one rule.
  • Sid is an optional label for humans.
  • Effect is Allow or Deny.
  • Action is one or more API actions in the form service:Operation, such as s3:GetObject or ec2:StartInstances. Wildcards work: s3:Get* matches every S3 action starting with Get.
  • Resource is the ARN or ARNs the statement is about. Wildcards work here too.
  • Condition (optional) makes the statement apply only when extra tests about the request pass.

Identity policies do not include a Principal, because the principal is whoever the policy is attached to. Resource policies and trust policies do include Principal.

Read the example aloud: "Allow reading and listing in the acme-reports bucket, but only when the caller signed in with MFA." Note the two resource ARNs. s3:ListBucket applies to the bucket (arn:aws:s3:::acme-reports), while s3:GetObject applies to the objects in it (.../*). Mixing these up is the most common reason that an S3 policy "does not work".

flowchart LR
    Q["Request<br/>who, action, resource, context"] --> D{"Explicit Deny<br/>matches?"}
    D -->|yes| X["Denied"]
    D -->|no| A{"Allow<br/>matches?"}
    A -->|yes| OK["Allowed"]
    A -->|no| N["Denied<br/>(implicit deny)"]

The basic decision flow: an explicit deny always wins, then an allow, otherwise the default is deny.

Three rules follow, and you should remember them forever:

  1. Everything is denied by default (implicit deny).
  2. An Allow statement that matches grants access.
  3. An explicit Deny always wins, no matter how many allows exist.

The next lesson, How Policy Evaluation Works, adds boundaries, organization policies and cross-account rules on top of this.

Wildcards and NotAction

* matches any run of characters (including none) and ? matches exactly one. They are the quickest way to write broad policies, and also the quickest way to grant far too much: "Action": "*", "Resource": "*" means "everything on everything", which is the administrator policy. Wildcards in the action name are fine when they follow a safe pattern like s3:Get*; a wildcard in the service part such as *:Delete* is a smell.

NotAction and NotResource invert the match: "everything except these". They are useful for statements like "deny everything except changing your own password when MFA is not present", but they are easy to misread, so use them rarely and with Deny only when you understand the effect.

Try it: a policy evaluator

The stand-in below evaluates a request against a list of statements, using the three rules above and wildcard matching on actions and resources. Run it, then change a statement and predict the answers before you run again.

Python Allow, Deny and the default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output shows that the same GetObject is allowed in one place and explicitly denied under secret/, that PutObject works only under uploads/, and that actions no statement mentions, like DeleteObject or anything in EC2, fall through to the implicit deny. Note how the first request is allowed only because of the /* resource: change that ARN to the bucket ARN alone and the object reads stop matching.

Conditions and policy variables

A Condition block has the shape { operator: { key: value } }. The key comes from the request's context, and the operator says how to compare. Common ones:

Operator Meaning
StringEquals, StringLike exact match, or match with wildcards
Bool true or false flag, such as aws:MultiFactorAuthPresent
IpAddress, NotIpAddress caller IP inside or outside a CIDR range
DateLessThan, DateGreaterThan time window
ArnLike match an ARN pattern

Useful condition keys include aws:SourceIp, aws:PrincipalTag/..., aws:RequestedRegion and s3:prefix. All conditions in one statement must pass (AND); several values for one key pass if any matches (OR).

Policy variables such as ${aws:username} are replaced by values from the request. They let one policy serve many users. This statement gives every user a private folder in a shared bucket:

JSON
{
  "Effect": "Allow",
  "Action": ["s3:GetObject", "s3:PutObject"],
  "Resource": "arn:aws:s3:::acme-home/${aws:username}/*"
}

The stand-in below adds a small set of condition operators and the ${aws:username} variable to the evaluator.

Python Conditions and a per-user folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two things to notice: Maya reaches her own folder but not Lee's although the policy is the same, because the variable resolved to her name; and the ec2:StopInstances statement needs both conditions, MFA and the source address, to pass.

Identity-based and resource-based policies

  • An identity-based policy is attached to a user, group or role. It says what that identity may do. It has no Principal.
  • A resource-based policy is attached to a resource, such as an S3 bucket, an SQS queue, a KMS key or a Lambda function. It says who may use that resource, so it has a Principal.
JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::222222222222:role/Uploader" },
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::acme-reports/uploads/*"
  }]
}

Within one account, an allow in either kind of policy is enough. Across accounts, both sides must agree: the resource's account must grant access and the caller's identity must also be allowed. Resource-based policies are how you let other accounts or AWS services use your resources without creating a user for them.

Managed and inline policies

  • AWS managed policies are created and updated by AWS, for example ReadOnlyAccess or AmazonS3ReadOnlyAccess. They are convenient, but they are broad and AWS may change them.
  • Customer managed policies are standalone policies you write once and attach to many identities. They are versioned, so you can roll back. This is the usual choice for your own permissions.
  • Inline policies are embedded in exactly one user, group or role and deleted with it. Use them when a policy truly belongs to one identity and must never be reused.

Prefer customer managed policies for anything shared, and write them as narrowly as you can; IAM Best Practices and Least Privilege shows how to tighten them over time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request matches one Allow statement and one Deny statement. What is the result?

    An explicit Deny overrides any number of Allow statements.
  2. 2. What happens to a request that no statement mentions?

    IAM denies everything unless a policy explicitly allows it.
  3. 3. Why does the policy example list both arn:aws:s3:::acme-reports and arn:aws:s3:::acme-reports/*?

    Bucket-level actions use the bucket ARN, object-level actions use the object ARN pattern.
  4. 4. Which element do resource-based policies have that identity-based policies lack?

    A resource policy must say who it applies to, so it has a Principal. An identity policy applies to whoever it is attached to.
  5. 5. Which kind of policy is best for a permission set reused by many roles that you want to version?

    Customer managed policies are standalone and versioned, so one definition can be attached to many identities.

Summary

  • A policy is JSON with Version, Statement, and per statement Effect, Action, Resource and optionally Condition.
  • Default deny, allow grants, and an explicit deny always wins.
  • Wildcards * and ? are powerful and dangerous; conditions and variables narrow access by context such as MFA, IP address or user name.
  • Identity policies say what an identity can do; resource policies say who can use a resource and carry a Principal.
  • Prefer customer managed policies for reuse; use inline policies only for one-off, tightly bound permissions.

Next: How Policy Evaluation Works.