# IAM: who can do what

Users, groups, policies and roles, clicked through in the real console: write a least-privilege policy, give it to a group, add a user, set up MFA and prove what the user can and cannot do.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 2. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/02-iam

## What you will learn

- Explain users, groups, roles and policies, and when to use each
- Read a policy and say what Effect, Action, Resource and Condition do
- Create a customer managed policy, a group and a user in the console, step by step
- Turn on MFA, and keep long-lived access keys to a minimum
- Use roles and temporary credentials for EC2, CI/CD and cross-account access
- Prove what an identity can do with the policy simulator

## Every request asks one question

Before IAM, a team might share one administrator password and pass it around whenever somebody needed to
change AWS. It was quick at first, but nobody could tell who made a change, and a leaked password gave an
attacker the whole account. IAM (Identity and Access Management) replaces that shared login with named
identities and explicit permissions.

Every console click and `aws` command becomes an API request. IAM evaluates the identity making the request,
the action it wants, the resource it targets and any conditions attached to the policy. The default is deny:
an identity needs an applicable allow, and an explicit deny takes precedence. In the example below, the
identity returned by STS is useful context, but it does not prove that a later action will be allowed.

The basic building blocks are:

| Piece      | What it is                                                                      | Example                                                |
| ---------- | ------------------------------------------------------------------------------- | ------------------------------------------------------ |
| **User**   | a person or app with long-term credentials                                      | `demo-dev`                                             |
| **Group**  | a set of users that share permissions                                           | `developers`                                           |
| **Role**   | an identity anyone trusted can _assume_ for a while, with temporary credentials | an EC2 server, a CI job, an admin from another account |
| **Policy** | a JSON document listing what's allowed or denied                                | `academy-s3-read`                                      |

> **Figure.** Who is asking: the user demo-dev, member of the group developers which has the policy academy-s3-read attached, or a role assumed by an EC2 server or CI job with temporary credentials. The request: action s3:GetObject on arn:aws:s3:::academy-reports/q3.csv, with context such as MFA and source IP. IAM decides in order: if any policy explicitly denies it, deny; else if any policy allows this action on this resource, allow; else deny by default.
>
> An explicit deny always wins. Otherwise a matching allow is needed, and without one the answer is deny.

Find out who you are right now:

```sh
$ aws sts get-caller-identity
{
    "UserId": "AIDA…",
    "Account": "111122223333",
    "Arn": "arn:aws:iam::111122223333:user/anythinkX"
}
```

The screenshots and outputs in this lesson come from a real practice account. The account ID is replaced with
`111122223333`, the example ID AWS uses in its own documentation, and other users' names are blurred.

For a human, prefer a federated sign-in through IAM Identity Center rather than a long-lived IAM user. For an
application running on AWS, attach a role so it receives temporary credentials. Use an IAM user only when a
specific integration still requires long-lived credentials, and limit and rotate those keys. A common mistake
is granting `AdministratorAccess` just to get past an `AccessDenied` error. Identify the failed action and
resource, then add only the permission the job needs.

## Reading a policy

This policy lets someone list buckets and read objects, and nothing else:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadOnlyS3",
      "Effect": "Allow",
      "Action": ["s3:ListAllMyBuckets", "s3:ListBucket", "s3:GetObject"],
      "Resource": "*"
    }
  ]
}
```

| Field       | Meaning                                                         |
| ----------- | --------------------------------------------------------------- |
| `Effect`    | `Allow` or `Deny`                                               |
| `Action`    | API calls, as `service:Action`; wildcards like `s3:Get*` work   |
| `Resource`  | which things, by ARN: `arn:aws:s3:::my-bucket/*`; `*` means all |
| `Condition` | optional extra rules: source IP, MFA present, tags, time        |

Three rules decide every request: **everything is denied by default**, an `Allow` opens it, and an explicit
`Deny` beats any `Allow`.

Policies come in three kinds: **AWS managed** (written by AWS, like `AmazonS3ReadOnlyAccess`), **customer
managed** (yours, reusable, versioned) and **inline** (stuck to one identity; avoid them). The ones above are
_identity-based_: attached to a user, group or role. _Resource-based_ policies, such as an S3 bucket policy,
sit on the resource and say who may use it.

### Create it in the console

**IAM → Policies → Create policy** opens the policy editor. Switch from **Visual** to **JSON** and paste the
policy:

> **Figure.** AWS console, IAM, Create policy, step 1 Specify permissions. The Policy editor has Visual and JSON tabs and an empty Select a service section, with Next at the bottom right.
>
> (1) Switch the editor to JSON and paste the policy. (2) Next, to name and review it.

Click **Next**, name it `academy-s3-read`, add a description and **Create policy**. Its page shows what it
allows, in plain words:

> **Figure.** The academy-s3-read policy page. Type Customer managed, with creation time. The Permissions tab shows Allow 1 of 476 services: S3, access level Limited: List, Read, on all resources, no request condition.
>
> The summary reads the JSON for you: S3 only, List and Read only.

The same from the CLI:

```sh
$ aws iam create-policy --policy-name academy-s3-read --policy-document file://pol.json
```

## Users and groups

Give permissions to **groups**, then put users in them. When someone changes team, you move them between
groups instead of editing policies person by person.

**IAM → User groups → Create group:** name it `developers`, search for `academy-s3-read` and tick it.

> **Figure.** Create user group page. User group name: developers. Add users to the group is optional and left empty; the existing users are blurred. Attach permissions policies is filtered to academy-s3-read, Customer managed, and ticked. Create user group button at the bottom right.
>
> (1) Name the group. (2) Search for and tick academy-s3-read. (3) Create user group. Adding users here is optional.

> **Figure.** Green banner: developers user group created. The groups list shows developers with 0 users, permissions Defined, created Now.
>
> Created. 0 users so far, permissions Defined.

Now the user. **IAM → Users → Create user**, three steps:

> **Figure.** Create user, step 1 Specify user details. User name demo-dev. The checkbox Provide user access to the AWS Management Console is left unticked. A note says access keys can be generated after the user is created.
>
> (1) The user name. (2) Console access stays off for this demo. (3) Next.

> **Figure.** Create user, step 2 Set permissions. Permissions option Add user to group is selected. The User groups table shows developers, 0 users, attached policy academy-s3-read, ticked.
>
> (1) Add user to group. (2) Tick developers, which already carries the policy. (3) Next.

> **Figure.** Create user, step 3 Review and create. User name demo-dev, console password type None, require password reset No. Permissions summary: developers, type Group, used as Permissions group. No tags. Create user button.
>
> (1) Check the user gets its permissions from the developers group. (2) Create user.

From the CLI it's two commands:

```sh
$ aws iam create-user --user-name demo-dev
$ aws iam add-user-to-group --user-name demo-dev --group-name developers
```

## MFA

A password alone is one phishing email away from gone. **Multi-factor authentication** adds a code from a
device you hold. Open the user, **Security credentials** tab:

> **Figure.** demo-dev user page, Security credentials tab. Summary: console access Disabled, no access keys. Console sign-in is not enabled. Multi-factor authentication (MFA) shows 0 devices with an Assign MFA device button. Access keys (0) with a Create access key button.
>
> (1) Assign MFA device starts the MFA setup. (2) Access keys: 0, the safest number.

**Assign MFA device** asks for a name and the type:

> **Figure.** Assign MFA device, step 1 Select MFA device. Device name demo-dev-phone. Device options: Passkey or security key, Authenticator app (selected), and Hardware TOTP token.
>
> (1) Name the device. (2) Authenticator app is the common choice; a passkey or security key resists phishing better.

Step 2 shows a QR code: scan it with an authenticator app and type two codes in a row. Do it **first for the
root user** (the email you signed up with), then for every human user. The account summary tells you whether
root has it:

```sh
$ aws iam get-account-summary --query 'SummaryMap.{Users:Users,MFADevices:MFADevices,AccountMFAEnabled:AccountMFAEnabled}'
{
    "Users": 2,
    "MFADevices": 2,
    "AccountMFAEnabled": 1
}
```

`AccountMFAEnabled: 1` means the root user has MFA.

> **Video.** [Guide to Securing Your AWS Account for New Users | Amazon Web Services](https://www.youtube.com/watch?v=oPXxwMmLPA4&t=186s) (Amazon Web Services)

## Access keys

An **access key** (an ID starting `AKIA` plus a secret) lets the CLI and SDKs act as a user. It never expires
on its own, so it's the credential that leaks most: committed to git, baked into an image, pasted in a chat.

- Prefer **no keys**: humans use IAM Identity Center (`aws sso login`), servers and CI use roles.
- If you must have one, one per person, never for root, stored by `aws configure` (not in code), and **rotated**:
  create a new key, switch to it, deactivate the old one, delete it.
- A key that leaked is a key to delete now, not later: bots scan public GitHub for `AKIA` within minutes.

## Roles and temporary credentials

A **role** has no password or keys. Something it _trusts_ assumes it and gets credentials that expire, usually
after an hour. Assume a role from the CLI:

```sh
$ aws sts assume-role --role-arn arn:aws:iam::111122223333:role/academy-console --role-session-name lesson-demo \
    --query '{Arn:AssumedRoleUser.Arn,Expires:Credentials.Expiration}'
{
    "Arn": "arn:aws:sts::111122223333:assumed-role/academy-console/lesson-demo",
    "Expires": "2026-10-17T09:09:02+00:00"
}
```

Every role has two policies: the **trust policy** (who may assume it) and **permissions policies** (what it can
do once assumed). The console's **Create role** starts with the trust side:

> **Figure.** Create role, step 1 Select trusted entity. Trusted entity type options: AWS service (selected), AWS account, Web identity, SAML 2.0 federation, Custom trust policy. Use case: Service or use case dropdown, Choose a service or use case.
>
> (1) Who may use the role: here an AWS service. (2) Which one, such as EC2. This is the role's trust policy.

| Trusted entity        | Real use                                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------------------------- |
| **AWS service → EC2** | an **instance profile**: the app on the server gets credentials from the instance, no keys on disk (lesson 3) |
| **AWS account**       | **cross-account access**: admins in a security account assume a role in production                            |
| **Web identity**      | **OIDC for CI/CD**: GitHub Actions assumes a role for one job, no stored AWS keys (the CI/CD course)          |
| **SAML 2.0**          | a company login (Okta, Entra ID) mapped to AWS roles                                                          |

> **Video.** [AWS IAM Roles | Amazon Web Services](https://www.youtube.com/watch?v=miij_0HkBws) (Amazon Web Services)

## Prove it: the policy simulator

Don't guess what a policy allows: test it before relying on it. The IAM policy simulator evaluates a proposed
request against policies without calling S3, launching an instance or changing a resource. This makes it a
safe way to catch a missing permission or an unexpected deny.

The command names a principal, lists four actions and asks for only each action's decision. `allowed` means
the simulator found an applicable allow and no overriding deny. `implicitDeny` means no allow matched; an
explicit `Deny` is reported separately. The simulator does not prove that the action will succeed in every
real request: service control policies, resource policies, permissions boundaries, session policies and
request conditions can also affect access.

```sh
$ aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:user/demo-dev \
    --action-names s3:GetObject s3:PutObject s3:DeleteBucket ec2:RunInstances \
    --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table
--------------------------------------
|       SimulatePrincipalPolicy      |
+-------------------+----------------+
|  s3:GetObject     |  allowed       |
|  s3:PutObject     |  implicitDeny  |
|  s3:DeleteBucket  |  implicitDeny  |
|  ec2:RunInstances |  implicitDeny  |
+-------------------+----------------+
```

`demo-dev` can read objects and nothing else. **Least privilege** is exactly this: start with nothing and allow
only what the job needs. **IAM Access Analyzer** helps keep it that way: it finds resources shared outside the
account and permissions nobody has used for months.

> **Video.** [How do I use the IAM policy simulator to test IAM policies and permissions?](https://www.youtube.com/watch?v=sI-SyOvHeno) (Amazon Web Services)

Use the simulator while authoring a policy, then verify in a non-production account with the same role and
request context the workload will use. For organization-wide analysis, IAM Access Analyzer can identify
external access and generate policy suggestions from observed activity. A common mistake is treating a
simulator result as a live authorization test; it simulates the policies and inputs you supply, not every
runtime condition or service-side failure.

## Guard rails for bigger teams

One account and one admin are easy to start with, but they provide a weak boundary as a team grows. A
permission mistake in a test environment can then affect production, and every person must be managed in
every account. AWS offers controls at different levels: IAM Identity Center manages workforce sign-in,
Organizations groups accounts, service control policies set an outer permission ceiling, and permission
boundaries constrain what delegated administrators can grant. These controls complement identity policies;
they do not replace careful resource permissions.

Use a separate account for production and security-sensitive workloads when you need stronger blast-radius
separation. Put only the minimum shared rules at the organization level, and test policy changes in a
non-production account. The common mistake is to assume an organization-level deny is a substitute for
least-privilege roles inside each account.

## IAM Identity Center is the human access portal

IAM users are a poor fit for a team: each account grows another password and another long-lived key. IAM
Identity Center gives a person one sign-in portal, then assigns a permission set to a role in each account.
The role supplies temporary credentials, so removing access means removing the assignment rather than hunting
for keys. Use it for workforce access; keep IAM roles for workloads.

In the console, open **IAM Identity Center → Settings** and read the enable page and settings page. Do not press
Enable. A read-only CLI check, when an organization already has an instance, is:

```sh
$ aws sso-admin list-instances --region ap-south-1 \
    --query 'Instances[].{Status:Status,IdentityStore:IdentityStoreId}' --output table
```

Permission sets are reusable policy bundles. Assign one to a group and account, then let the person use the
access portal for temporary credentials.

## ABAC uses tags as a permission condition

Attribute-based access control compares a principal tag with a resource tag. It scales better than one policy per
team, but only if tag changes are restricted and audited:

```json
{"Effect":"Allow","Action":"ec2:StopInstances","Resource":"*","Condition":{"StringEquals":{"ec2:ResourceTag/Project":"${aws:PrincipalTag/Project}"}}}
```

Use fixed resource ARNs for a small, high-risk set where the boundary must be obvious.

- **IAM Identity Center (SSO):** one login for people across all your accounts, with temporary credentials
  instead of IAM users. AWS recommends it for human access.
- **AWS Organizations:** many accounts (dev, staging, prod, security) under one bill, so a mistake in dev can't
  touch prod.
- **Service control policies (SCPs):** an organisation-wide ceiling: even an admin in a member account can't
  do what an SCP denies, such as leaving approved Regions or turning off CloudTrail.
- **Permission boundaries:** a ceiling on one user or role, so you can let a team create roles without letting
  them create something more powerful than themselves.

> **Lock the root user away.** The root user can do everything, including closing the account, and no policy can limit it. Give it MFA and a strong unique password, delete any root access keys, and use it only for the few tasks that need it, such as changing the account's support plan.

> **In production.** People sign in through IAM Identity Center with MFA, workloads use roles, CI uses OIDC, and long-lived access keys are the rare exception, rotated and monitored. Review unused permissions with Access Analyzer every few months, and keep separate accounts for production.

## Mission: A least-privilege developer

In your own account, create the academy-s3-read policy, a developers group with it attached and a demo-dev user in the group, following the screenshots. Prove with the policy simulator that demo-dev can read S3 objects but not write them or start servers, then delete everything you created.

- You need: An AWS account where you can use IAM, with the AWS CLI configured
- You'll have: A simulator table with allowed for s3:GetObject and implicitDeny for the rest, then no demo-dev, developers or academy-s3-read left

```sh
$ printf '%s\n' '{"Version":"2012-10-17","Statement":[{"Sid":"ReadOnlyS3","Effect":"Allow","Action":["s3:ListAllMyBuckets","s3:ListBucket","s3:GetObject"],"Resource":"*"}]}' > pol.json
$ ACC=$(aws sts get-caller-identity --query Account --output text)
$ aws iam create-policy --policy-name academy-s3-read --policy-document file://pol.json
$ aws iam create-group --group-name developers
$ aws iam attach-group-policy --group-name developers --policy-arn arn:aws:iam::$ACC:policy/academy-s3-read
$ aws iam create-user --user-name demo-dev
$ aws iam add-user-to-group --user-name demo-dev --group-name developers
$ aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::$ACC:user/demo-dev \
    --action-names s3:GetObject s3:PutObject ec2:RunInstances \
    --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
s3:GetObject	allowed
s3:PutObject	implicitDeny
ec2:RunInstances	implicitDeny
$ aws iam remove-user-from-group --user-name demo-dev --group-name developers
$ aws iam delete-user --user-name demo-dev
$ aws iam detach-group-policy --group-name developers --policy-arn arn:aws:iam::$ACC:policy/academy-s3-read
$ aws iam delete-group --group-name developers
$ aws iam delete-policy --policy-arn arn:aws:iam::$ACC:policy/academy-s3-read
```

IAM is free, so this costs nothing. The order of the clean-up matters: a group with members, or a policy still
attached, can't be deleted.

## Try it

- Run `aws sts get-caller-identity` and read which identity your CLI is using.
- Open IAM → Policies, filter by Customer managed, and read one policy's JSON.
- Create the `developers` group and `demo-dev` user from this lesson, then delete them.
- Run `aws iam simulate-principal-policy` for s3:GetObject and s3:PutObject and compare the results.
- Open the IAM dashboard and check the root user has MFA.
- Start creating a role for EC2 and stop at the trusted entity page: who is allowed to use it?

## Quiz

1. A new developer needs read access to S3. What is the best way to give it?
   - Share your access keys
   - Attach AdministratorAccess to their user
   - **Add their user to a group whose policy allows only the S3 read actions they need** (answer)
   Why: Groups hold the permissions; users just join. Least privilege means only the actions the job needs.

2. An app on EC2 must read from S3. How should it get credentials?
   - Put an access key in the app's config file
   - **Attach an IAM role to the instance (an instance profile), so it gets temporary credentials automatically** (answer)
   - Use the root user's keys
   Why: Roles hand out short-lived credentials that rotate themselves. Keys in files leak through git, images and backups.

3. A policy allows s3:GetObject. The user tries s3:PutObject. What happens?
   - It is allowed, because S3 is allowed
   - **It is denied, because nothing allows it (implicit deny)** (answer)
   - AWS asks the user
   Why: Everything is denied unless a policy allows it. The simulator showed implicitDeny for PutObject.

4. An explicit Deny and an Allow both match a request. Which wins?
   - The Allow
   - **The explicit Deny, always** (answer)
   - The newer policy
   Why: An explicit Deny overrides any Allow. That's how guard rails like SCPs and permission boundaries work.

5. Which identity should you use for everyday work?
   - The root user, with MFA
   - **An IAM Identity Center user or IAM user (or role) with MFA, and the root user locked away** (answer)
   - A shared admin user for the whole team
   Why: Root can do everything, including closing the account. Use it only for the few tasks that need it.

## Resources

- [IAM user guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) (AWS Docs)
- [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) (AWS Docs)
- [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) (AWS Docs)
- [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) (AWS Docs)
- [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) (AWS Docs)
