Overview and What You Will Learn
AWS Identity and Access Management (IAM) decides who can do what in your AWS account, and every API call passes through it. It answers two questions for each request: who are you (authentication) and what are you allowed to do (authorization). In this lab you build groups, users and an EC2 role from the CLI, test their permissions with the policy simulator, and audit the account with a Credential Report and IAM Access Analyzer.
By the end you will be able to:
- Explain the root user and why it is locked down
- Use users, groups and roles correctly, and know when to use each
- Read and write IAM policies, and explain why an explicit Deny always wins
- Replace long-lived access keys with roles and short-lived credentials
- Set up MFA, password rules and safe access key handling
- Audit an account with the Credential Report, Access Advisor and Access Analyzer
Why This Matters in Production
Most serious AWS incidents trace back to IAM: access keys committed to a public repository, roles with far more permission than they need, and users who left the company but still have active credentials. IAM is also not a one-time setup. Teams grow, services change, and permissions drift, so access has to be reviewed and tightened regularly.
The goal is least privilege, meaning every person and workload gets only the permissions it needs, so a stolen credential does limited damage.
Core Principles
What Is the AWS Root User and When Should You Use It?
The root user is the identity created with the account email and password, and it has full access to everything in the account. IAM policies cannot restrict it, although service control policies in AWS Organizations can restrict the root user of member accounts. If root credentials are stolen, the whole account is compromised.
- Turn on MFA for root immediately, and never create access keys for root
- Use root only for the small set of tasks that require it, such as changing account settings, closing the account, or restoring IAM access
- Create an administrative identity for daily work and keep the root credentials in a safe place
- In an AWS Organization, central root access management can remove root credentials from member accounts
SecurityTreat root like the master key to the building. It is locked away, protected with MFA, and used only in genuine emergencies.
How Do IAM Users, Groups, and Roles Fit Together?
Users are identities for people or applications, groups collect users who share a job so permissions are managed once, and roles give temporary permissions to whoever or whatever assumes them. AWS recommends that people sign in through IAM Identity Center and use temporary credentials, with IAM users kept for specific cases that cannot use it.
- One person is one user. Shared users make auditing and revocation impossible
- A group holds users only, and groups cannot be nested
- A user can be in several groups, and permissions from all of them combine
- Attach policies to groups, not to individual users, so a role change is just a group change
RememberIAM is global. A user or role you create works in every Region.
How Do You Read an IAM Policy?
A policy is a JSON document whose statements each allow or deny actions on resources, optionally under conditions. Every statement is evaluated together, and the order of statements does not matter. Here is a policy that lets someone read one bucket and blocks deletes, shown by statement:
| Statement | Effect | Action | Resource |
|---|---|---|---|
| AllowReadPaymentLogs | Allow | s3:ListBucket | arn:aws:s3:::devops-payment-logs |
| AllowReadPaymentLogs | Allow | s3:GetObject | arn:aws:s3:::devops-payment-logs/* |
| ExplicitlyDenyDelete | Deny | s3:DeleteObject | arn:aws:s3:::devops-payment-logs/* |
| Element | Required | Purpose |
|---|---|---|
| Version | Yes | Policy language version, use 2012-10-17 |
| Sid | No | A label that helps audits |
| Effect | Yes | Allow or Deny |
| Action | Yes | API calls, such as s3:GetObject |
| Resource | Yes for identity policies | The ARN the statement applies to |
| Principal | Resource and trust policies | Who the policy applies to |
| Condition | No | Extra rules such as IP range or MFA |
RememberAn explicit Deny always beats any Allow, whichever policy it comes from. If nothing allows an action, it is denied by default.
Common MistakeUsing the wrong S3 ARN. Bucket-level actions such as s3:ListBucket need the bucket ARN, and object actions such as s3:GetObject need the ARN ending in /*. Reading files usually needs both.
Which Policy Type Should You Use?
Prefer AWS managed policies for common jobs and customer managed policies for your own rules, and avoid inline policies. Managed policies can be attached to many identities and versioned, while inline policies live on one user or role and are hard to find during audits.
| Type | Created by | Use for |
|---|---|---|
| AWS managed | AWS | Standard jobs such as AmazonS3ReadOnlyAccess |
| Customer managed | You | Rules specific to your organisation |
| Inline | You, on one identity | Rare one-off cases |
Why Use IAM Roles Instead of Access Keys?
A role gives an AWS service or federated person temporary credentials that expire and rotate automatically, so there is nothing long-lived to leak. An EC2 instance, Lambda function or ECS task assumes a role, and the SDK fetches and refreshes credentials on its own. Roles have a trust policy, which says who may assume them, and permission policies, which say what they can do.
| IAM user | IAM role | |
|---|---|---|
| Credentials | Long-term keys | Temporary, auto-rotated |
| Risk if leaked | High until rotated | Limited by expiry |
| Typical use | A person or legacy tool | EC2, Lambda, ECS, CI jobs |
Common roles include an EC2 instance role, a Lambda execution role, an ECS task role and a CloudFormation service role.
TipIf you are about to put an access key on an EC2 instance, in a Lambda function or inside a container, stop and create a role. Also require IMDSv2 on instances, which makes stealing role credentials through the metadata service harder.
How Do You Protect Sign-In with MFA and Passwords?
MFA adds a second factor so a stolen password alone is not enough. Use passkeys or FIDO2 security keys where you can, authenticator apps next, and hardware TOTP tokens where required.
- Require MFA for every human user, and enforce it with a policy condition for sensitive actions
- Set a password policy under account settings: a minimum length of 12 or more, character types, user password changes, and reuse prevention
- Forced periodic expiry is optional, because current guidance prefers strong passwords with MFA over frequent rotation
How Should You Handle Access Keys?
Treat an access key like a password: it is a secret pair, and anyone holding it acts as that user. Whenever possible use roles or IAM Identity Center with aws configure sso, which gives short-lived CLI credentials with no stored keys.
- Never commit keys to Git or hardcode them in source
- Never share keys, since each person or system gets its own
- A user can have at most two access keys, which allows rotation without downtime
- Deactivate suspected leaks at once, then delete them after confirming nothing breaks
- Use keys only where nothing else works, and rotate them
AWS CloudShell is a browser-based terminal that is already signed in, which is useful for quick commands.
How Do You Audit IAM Over Time?
Use four tools together: the Credential Report for a whole-account snapshot, Access Advisor for what a principal actually uses, Access Analyzer for external and unused access, and the policy simulator for testing. Permissions drift as people leave and services change, so run these on a schedule.
| Tool | What it shows |
|---|---|
| Credential Report | Every user's password, MFA and key status, with last-used dates |
| Access Advisor | Which services a user or role has accessed, and when |
| Access Analyzer | Resources shared outside your account, and unused access |
| Policy simulator | Whether an identity is allowed a given action |
Access Advisor makes trimming practical. If a user has EC2, S3, RDS and Lambda access but Access Advisor shows RDS and Lambda were never used, remove those two and the stolen-credential blast radius shrinks. Access Analyzer can also generate a least-privilege policy from CloudTrail activity.
Detailed Step-by-Step Practical Lab
This lab runs in a test account. Policy documents are generated with small Python snippets so no hand-written JSON is needed.
Step 1: Protect the root user
In the console, sign in as root, open Security credentials, and assign an MFA device. Do not create root access keys. Then create an administrative identity, preferably in IAM Identity Center, and use it for all daily work.
Step 2: Create groups and a user
aws iam create-group --group-name Developersaws iam attach-group-policy --group-name Developers \ --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccessaws iam attach-group-policy --group-name Developers \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess aws iam create-group --group-name Testersaws iam attach-group-policy --group-name Testers \ --policy-arn arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess aws iam create-user --user-name arjun-devaws iam add-user-to-group --user-name arjun-dev --group-name Developers aws iam list-groups-for-user --user-name arjun-devaws iam list-attached-group-policies --group-name DevelopersStep 3: Test permissions with the policy simulator
USER_ARN=$(aws iam get-user --user-name arjun-dev --query User.Arn --output text) aws iam simulate-principal-policy \ --policy-source-arn $USER_ARN \ --action-names s3:ListAllMyBuckets ec2:RunInstances iam:ListUsers \ --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output tableThe S3 and EC2 actions show allowed, and iam:ListUsers shows implicitDeny because no policy grants it. No access key is needed to test this.
Step 4: Create an EC2 role
python3 - <<'EOF'import jsontrust = dict( Version='2012-10-17', Statement=[dict( Effect='Allow', Principal=dict(Service='ec2.amazonaws.com'), Action='sts:AssumeRole', )],)json.dump(trust, open('ec2-trust.json', 'w'), indent=2)EOF aws iam create-role --role-name ec2-s3-read-role \ --assume-role-policy-document file://ec2-trust.jsonaws iam attach-role-policy --role-name ec2-s3-read-role \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess aws iam create-instance-profile --instance-profile-name ec2-s3-read-roleaws iam add-role-to-instance-profile \ --instance-profile-name ec2-s3-read-role --role-name ec2-s3-read-roleAttach the profile to an instance and check the identity from the instance:
aws ec2 associate-iam-instance-profile \ --instance-id i-0abc123def4567890 \ --iam-instance-profile Name=ec2-s3-read-role aws sts get-caller-identityaws s3 lsThe caller identity shows an assumed-role ARN, which confirms the instance uses the role and not a stored key.
Step 5: Review the Credential Report
aws iam generate-credential-reportaws iam get-credential-report --query Content --output text | base64 --decode > report.csv python3 - <<'EOF'import csvfor r in csv.DictReader(open('report.csv')): print(r['user'], r['mfa_active'], r['password_last_used'], r['access_key_1_last_used_date'])EOFLook for users without MFA, passwords never used, and old or unused access keys.
Step 6: Check last accessed services and external access
JOB=$(aws iam generate-service-last-accessed-details --arn $USER_ARN \ --query JobId --output text)aws iam get-service-last-accessed-details --job-id $JOB \ --query 'ServicesLastAccessed[].[ServiceNamespace,LastAuthenticated]' --output table aws accessanalyzer create-analyzer --analyzer-name devops-analyzer --type ACCOUNTaws accessanalyzer list-analyzersFindings from the analyzer list resources shared outside the account. An empty list is a good result.
Step 7: Clean up
aws iam remove-role-from-instance-profile \ --instance-profile-name ec2-s3-read-role --role-name ec2-s3-read-roleaws iam delete-instance-profile --instance-profile-name ec2-s3-read-roleaws iam detach-role-policy --role-name ec2-s3-read-role \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccessaws iam delete-role --role-name ec2-s3-read-role aws iam remove-user-from-group --user-name arjun-dev --group-name Developersaws iam delete-user --user-name arjun-devaws iam detach-group-policy --group-name Developers \ --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccessaws iam detach-group-policy --group-name Developers \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccessaws iam delete-group --group-name Developersaws iam detach-group-policy --group-name Testers \ --policy-arn arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccessaws iam delete-group --group-name Testers aws accessanalyzer delete-analyzer --analyzer-name devops-analyzerProduction Best Practices & Common Pitfalls
- Lock down root: MFA, no access keys, and only rare use.
- Use IAM Identity Center for people: It gives short-lived credentials and central control.
- Use roles for workloads: Never store access keys on EC2, in Lambda or in containers.
- One identity per person or system: Shared users destroy accountability.
- Manage permissions on groups: Move people between groups when roles change.
- Start from least privilege: Begin narrow, then use Access Advisor and Access Analyzer to refine.
- Require MFA for sensitive actions: Enforce it in policy conditions.
- Review monthly: Run the Credential Report, deactivate stale keys, and delete users who left.
- Prefer customer managed policies over inline: They are easier to audit and reuse.
Common MistakeRunning
aws configureon a server and storing keys there. If the server is compromised, so is the account, so use an instance role instead.
Common MistakeSharing one IAM user across a team. You cannot tell who did what, and revoking one person revokes everyone.
SecurityAccess keys that were never used, or not used for 90 days, are leaks waiting to happen. Deactivate them, wait a week to see if anything breaks, then delete them.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Who am I | aws sts get-caller-identity |
| List users | aws iam list-users |
| List a user's groups | aws iam list-groups-for-user --user-name <name> |
| Attach a managed policy to a group | aws iam attach-group-policy --group-name <g> --policy-arn <arn> |
| Test an action | aws iam simulate-principal-policy --policy-source-arn <arn> --action-names <action> |
| List access keys | aws iam list-access-keys --user-name <name> |
| Deactivate a key | aws iam update-access-key --user-name <name> --access-key-id <id> --status Inactive |
| Credential report | aws iam generate-credential-report |
| Problem | Likely cause and fix |
|---|---|
| AccessDenied despite an Allow | An explicit Deny, a permission boundary or an SCP. Check them all. |
| S3 policy works for listing but not reading | Missing the /* object ARN. Add both resources. |
| EC2 cannot use the role | Instance profile not attached, or the trust policy does not name ec2.amazonaws.com. |
| Cannot sign in with MFA | Clock drift or device lost. Re-sync, or have an admin reset the device. |
| Cross-account call denied | Both accounts must allow it. Check identity and resource policies. |
| Credential report is stale | It refreshes at most every few hours. Generate it again later. |