Claude Skill

iam

AWS Identity and Access Management for users, roles, policies, and permissions. Use when creating IAM policies, configuring cross-account access, setting up service roles, troubleshooting permission errors, or managing access control.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download itsmostafa-aws-agent-skills-skills_iam-e786d25.zip · 7 KB
Part of itsmostafa/aws-agent-skills — 17 skills

Install

skills CLI npx skills add https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/iam
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install itsmostafa-aws-agent-skills@llmmart
Git git clone https://github.com/itsmostafa/aws-agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole itsmostafa/aws-agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

AWS IAM

AWS Identity and Access Management (IAM) enables secure access control to AWS services and resources. IAM is foundational to AWS security—every AWS API call is authenticated and authorized through IAM.

Table of Contents

Core Concepts

Principals

Entities that can make requests to AWS: IAM users, roles, federated users, and applications.

Policies

JSON documents defining permissions. Types:

  • Identity-based: Attached to users, groups, or roles
  • Resource-based: Attached to resources (S3 buckets, SQS queues)
  • Permission boundaries: Maximum permissions an identity can have
  • Service control policies (SCPs): Organization-wide limits

Roles

Identities with permissions that can be assumed by trusted entities. No permanent credentials—uses temporary security tokens.

Trust Relationships

Define which principals can assume a role. Configured via the role's trust policy.

Common Patterns

Create a Service Role for Lambda

AWS CLI:

# Create the trust policy
cat > trust-policy.json << 'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

# Create the role
aws iam create-role \
  --role-name MyLambdaRole \
  --assume-role-policy-document file://trust-policy.json

# Attach a managed policy
aws iam attach-role-policy \
  --role-name MyLambdaRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

boto3:

import boto3
import json

iam = boto3.client('iam')

trust_policy = {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {"Service": "lambda.amazonaws.com"},
            "Action": "sts:AssumeRole"
        }
    ]
}

# Create role
iam.create_role(
    RoleName='MyLambdaRole',
    AssumeRolePolicyDocument=json.dumps(trust_policy)
)

# Attach managed policy
iam.attach_role_policy(
    RoleName='MyLambdaRole',
    PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
)

Create Custom Policy with Least Privilege

cat > policy.json << 'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query"
      ],
      "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable"
    }
  ]
}
EOF

aws iam create-policy \
  --policy-name MyDynamoDBPolicy \
  --policy-document file://policy.json

Cross-Account Role Assumption

# In Account B (trusted account), create role with trust for Account A
cat > cross-account-trust.json << 'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111111111111:root" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": { "sts:ExternalId": "unique-external-id" }
      }
    }
  ]
}
EOF

# From Account A, assume the role
aws sts assume-role \
  --role-arn arn:aws:iam::222222222222:role/CrossAccountRole \
  --role-session-name MySession \
  --external-id unique-external-id

CLI Reference

Essential Commands

Command Description
aws iam create-role Create a new IAM role
aws iam create-policy Create a customer managed policy
aws iam attach-role-policy Attach a managed policy to a role
aws iam put-role-policy Add an inline policy to a role
aws iam get-role Get role details
aws iam list-roles List all roles
aws iam simulate-principal-policy Test policy permissions
aws sts assume-role Assume a role and get temporary credentials
aws sts get-caller-identity Get current identity

Useful Flags

  • --query: Filter output with JMESPath
  • --output table: Human-readable output
  • --no-cli-pager: Disable pager for scripting

Best Practices

Security

  • Never use root account for daily tasks
  • Enable MFA for all human users
  • Use roles instead of long-term access keys
  • Apply least privilege — grant only required permissions
  • Use conditions to restrict access by IP, time, or MFA
  • Rotate credentials regularly
  • Use permission boundaries for delegated administration

Policy Design

  • Start with AWS managed policies, customize as needed
  • Use policy variables (${aws:username}) for dynamic policies
  • Prefer explicit denies for sensitive actions
  • Group related permissions logically

Monitoring

  • Enable CloudTrail for API auditing
  • Use IAM Access Analyzer to identify overly permissive policies
  • Review credential reports regularly
  • Set up alerts for root account usage

Troubleshooting

Access Denied Errors

Symptom: AccessDeniedException or UnauthorizedAccess

Debug steps:

  1. Verify identity: aws sts get-caller-identity
  2. Check attached policies: aws iam list-attached-role-policies --role-name MyRole
  3. Simulate the action:
    aws iam simulate-principal-policy \
      --policy-source-arn arn:aws:iam::123456789012:role/MyRole \
      --action-names dynamodb:GetItem \
      --resource-arns arn:aws:dynamodb:us-east-1:123456789012:table/MyTable
    
  4. Check for explicit denies in SCPs or permission boundaries
  5. Verify resource-based policies allow the principal

Role Cannot Be Assumed

Symptom: AccessDenied when calling AssumeRole

Causes:

  • Trust policy doesn't include the calling principal
  • Missing sts:AssumeRole permission on the caller
  • ExternalId mismatch (for cross-account roles)
  • Session duration exceeds maximum

Fix: Review and update the role's trust relationship.

Policy Size Limits

  • Managed policy: 6,144 characters
  • Inline policy: 2,048 characters (user), 10,240 characters (role/group)
  • Trust policy: 2,048 characters

Solution: Use multiple policies, reference resources by prefix/wildcard, or use tags-based access control.

References

Files (aws-agent-skills)
  • best-practices.md 7.1 KB
    # IAM Security Best Practices
    
    Comprehensive security best practices for AWS IAM.
    
    ## Foundational Security
    
    ### Root Account Protection
    
    1. **Never use root for daily operations**
    2. **Enable MFA** on root account (hardware key preferred)
    3. **Delete root access keys** if they exist
    4. **Set up CloudWatch alarms** for root account usage:
    
    ```bash
    # Create metric filter for root login
    aws logs put-metric-filter \
      --log-group-name CloudTrail/DefaultLogGroup \
      --filter-name RootAccountUsage \
      --filter-pattern '{ $.userIdentity.type = "Root" }' \
      --metric-transformations \
        metricName=RootAccountUsageCount,metricNamespace=CloudTrailMetrics,metricValue=1
    
    # Create alarm
    aws cloudwatch put-metric-alarm \
      --alarm-name RootAccountUsage \
      --metric-name RootAccountUsageCount \
      --namespace CloudTrailMetrics \
      --statistic Sum \
      --period 300 \
      --threshold 1 \
      --comparison-operator GreaterThanOrEqualToThreshold \
      --evaluation-periods 1 \
      --alarm-actions arn:aws:sns:us-east-1:123456789012:security-alerts
    ```
    
    ### User Management
    
    1. **Use IAM Identity Center (SSO)** for human access
    2. **Enforce MFA** for all console users
    3. **Set password policies**:
    
    ```bash
    aws iam update-account-password-policy \
      --minimum-password-length 14 \
      --require-symbols \
      --require-numbers \
      --require-uppercase-characters \
      --require-lowercase-characters \
      --max-password-age 90 \
      --password-reuse-prevention 24
    ```
    
    4. **Review and remove unused credentials**:
    
    ```bash
    # Generate credential report
    aws iam generate-credential-report
    
    # Get the report
    aws iam get-credential-report --query Content --output text | base64 -d
    ```
    
    ## Least Privilege Implementation
    
    ### Principles
    
    1. **Start with zero permissions**, add as needed
    2. **Use AWS managed policies** as starting points
    3. **Scope resources explicitly** — avoid `*` where possible
    4. **Use conditions** to further restrict access
    5. **Separate duties** — different roles for different functions
    
    ### Implementing Least Privilege
    
    **Step 1: Analyze required permissions**
    
    Use CloudTrail to see what actions are actually used:
    
    ```bash
    aws cloudtrail lookup-events \
      --lookup-attributes AttributeKey=Username,AttributeValue=developer-user \
      --start-time 2024-01-01 \
      --end-time 2024-01-31
    ```
    
    **Step 2: Use IAM Access Analyzer**
    
    ```bash
    # Create analyzer
    aws accessanalyzer create-analyzer \
      --analyzer-name MyAnalyzer \
      --type ACCOUNT
    
    # Generate policy from CloudTrail activity
    aws accessanalyzer start-policy-generation \
      --policy-generation-details '{
        "principalArn": "arn:aws:iam::123456789012:role/MyRole",
        "cloudTrailDetails": {
          "trailArn": "arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail",
          "startTime": "2024-01-01T00:00:00Z",
          "endTime": "2024-01-31T23:59:59Z"
        }
      }'
    ```
    
    **Step 3: Validate policies**
    
    ```bash
    aws iam simulate-principal-policy \
      --policy-source-arn arn:aws:iam::123456789012:role/MyRole \
      --action-names s3:GetObject s3:PutObject \
      --resource-arns arn:aws:s3:::my-bucket/*
    ```
    
    ## Attribute-Based Access Control (ABAC)
    
    Use tags for dynamic, scalable access control.
    
    ### Tag-Based Policy Example
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ec2:StartInstances",
            "ec2:StopInstances"
          ],
          "Resource": "*",
          "Condition": {
            "StringEquals": {
              "aws:ResourceTag/Project": "${aws:PrincipalTag/Project}",
              "aws:ResourceTag/Environment": "${aws:PrincipalTag/Environment}"
            }
          }
        }
      ]
    }
    ```
    
    ### Benefits of ABAC
    
    - **Scales automatically** — new resources inherit tags
    - **Reduces policy management** — fewer policies needed
    - **Enables self-service** — users manage tagged resources
    - **Audit-friendly** — clear relationship between principal and resource
    
    ## Role-Based Best Practices
    
    ### Service Roles
    
    1. **One role per function** — Lambda function A gets RoleA
    2. **Use service-linked roles** when available
    3. **Scope trust policies tightly**:
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "lambda.amazonaws.com"
          },
          "Action": "sts:AssumeRole",
          "Condition": {
            "StringEquals": {
              "aws:SourceAccount": "123456789012"
            },
            "ArnLike": {
              "aws:SourceArn": "arn:aws:lambda:us-east-1:123456789012:function:my-*"
            }
          }
        }
      ]
    }
    ```
    
    ### Cross-Account Roles
    
    1. **Always use External ID** for third-party access
    2. **Limit session duration** appropriately
    3. **Restrict source accounts explicitly**
    4. **Monitor assumeRole events** via CloudTrail
    
    ## Monitoring and Auditing
    
    ### Enable CloudTrail
    
    ```bash
    aws cloudtrail create-trail \
      --name ManagementEventsTrail \
      --s3-bucket-name my-cloudtrail-bucket \
      --is-multi-region-trail \
      --enable-log-file-validation
    ```
    
    ### Key Events to Monitor
    
    | Event | Description |
    |-------|-------------|
    | `CreateUser` | New IAM user created |
    | `CreateAccessKey` | New access key generated |
    | `AttachUserPolicy` | Policy attached to user |
    | `CreateRole` | New role created |
    | `UpdateAssumeRolePolicy` | Trust policy modified |
    | `ConsoleLogin` | Console access |
    | `AssumeRole` | Role assumption |
    
    ### IAM Access Analyzer
    
    Continuously analyzes policies to identify unintended access:
    
    ```bash
    # List findings
    aws accessanalyzer list-findings \
      --analyzer-arn arn:aws:access-analyzer:us-east-1:123456789012:analyzer/MyAnalyzer
    
    # Archive resolved findings
    aws accessanalyzer update-findings \
      --analyzer-arn arn:aws:access-analyzer:us-east-1:123456789012:analyzer/MyAnalyzer \
      --status ARCHIVED \
      --ids finding-id-1 finding-id-2
    ```
    
    ## Credential Rotation
    
    ### Access Key Rotation
    
    ```python
    import boto3
    from datetime import datetime, timedelta
    
    iam = boto3.client('iam')
    
    # List access keys
    response = iam.list_access_keys(UserName='my-user')
    
    for key in response['AccessKeyMetadata']:
        age = datetime.now(key['CreateDate'].tzinfo) - key['CreateDate']
        if age > timedelta(days=90):
            print(f"Key {key['AccessKeyId']} is {age.days} days old - rotate it!")
    
            # Create new key
            new_key = iam.create_access_key(UserName='my-user')
    
            # Deactivate old key (after updating applications)
            iam.update_access_key(
                UserName='my-user',
                AccessKeyId=key['AccessKeyId'],
                Status='Inactive'
            )
    ```
    
    ### Automation with AWS Config
    
    ```yaml
    # Config rule for access key rotation
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: access-keys-rotated
      Source:
        Owner: AWS
        SourceIdentifier: ACCESS_KEYS_ROTATED
      InputParameters:
        maxAccessKeyAge: 90
    ```
    
    ## Security Checklist
    
    - [ ] Root account MFA enabled
    - [ ] Root access keys deleted
    - [ ] IAM users have MFA
    - [ ] Password policy enforced
    - [ ] Unused credentials removed
    - [ ] Access keys rotated < 90 days
    - [ ] CloudTrail enabled
    - [ ] IAM Access Analyzer active
    - [ ] Permission boundaries in use
    - [ ] Service control policies defined (Organizations)
    - [ ] Roles used instead of users for applications
    - [ ] Cross-account access uses External ID
    - [ ] Policies follow least privilege
    - [ ] Credential report reviewed monthly
    
  • policies.md 6.7 KB
    # IAM Policy Patterns
    
    Detailed patterns and examples for IAM policies.
    
    ## Policy Structure
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "DescriptiveStatementId",
          "Effect": "Allow",
          "Action": ["service:Action"],
          "Resource": ["arn:aws:service:region:account:resource"],
          "Condition": {
            "ConditionOperator": {
              "ConditionKey": "value"
            }
          }
        }
      ]
    }
    ```
    
    ## Common Policy Patterns
    
    ### S3 Bucket Access
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "ListBucket",
          "Effect": "Allow",
          "Action": "s3:ListBucket",
          "Resource": "arn:aws:s3:::my-bucket",
          "Condition": {
            "StringLike": {
              "s3:prefix": ["${aws:username}/*"]
            }
          }
        },
        {
          "Sid": "ReadWriteObjects",
          "Effect": "Allow",
          "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
          "Resource": "arn:aws:s3:::my-bucket/${aws:username}/*"
        }
      ]
    }
    ```
    
    ### DynamoDB Table Access
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "dynamodb:GetItem",
            "dynamodb:PutItem",
            "dynamodb:UpdateItem",
            "dynamodb:DeleteItem",
            "dynamodb:Query"
          ],
          "Resource": [
            "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable",
            "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable/index/*"
          ]
        }
      ]
    }
    ```
    
    ### Lambda Execution with Logging
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
          ],
          "Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/*"
        }
      ]
    }
    ```
    
    ### Secrets Manager Access
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "secretsmanager:GetSecretValue",
            "secretsmanager:DescribeSecret"
          ],
          "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/*",
          "Condition": {
            "StringEquals": {
              "secretsmanager:ResourceTag/Environment": "production"
            }
          }
        }
      ]
    }
    ```
    
    ### EC2 Instance Management with Tags
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ec2:StartInstances",
            "ec2:StopInstances",
            "ec2:RebootInstances"
          ],
          "Resource": "arn:aws:ec2:*:*:instance/*",
          "Condition": {
            "StringEquals": {
              "aws:ResourceTag/Team": "${aws:PrincipalTag/Team}"
            }
          }
        },
        {
          "Effect": "Allow",
          "Action": "ec2:DescribeInstances",
          "Resource": "*"
        }
      ]
    }
    ```
    
    ## Condition Keys
    
    ### Common Global Condition Keys
    
    | Key | Description | Example |
    |-----|-------------|---------|
    | `aws:SourceIp` | Request IP address | Restrict to office IPs |
    | `aws:CurrentTime` | Current date/time | Allow only during business hours |
    | `aws:MultiFactorAuthPresent` | MFA used | Require MFA for sensitive actions |
    | `aws:PrincipalTag/key` | Tag on the principal | ABAC patterns |
    | `aws:ResourceTag/key` | Tag on the resource | ABAC patterns |
    | `aws:RequestedRegion` | Target region | Restrict to specific regions |
    
    ### MFA Enforcement
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Deny",
          "Action": "*",
          "Resource": "*",
          "Condition": {
            "BoolIfExists": {
              "aws:MultiFactorAuthPresent": "false"
            }
          }
        }
      ]
    }
    ```
    
    ### IP Restriction
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Deny",
          "Action": "*",
          "Resource": "*",
          "Condition": {
            "NotIpAddress": {
              "aws:SourceIp": ["192.0.2.0/24", "203.0.113.0/24"]
            }
          }
        }
      ]
    }
    ```
    
    ### Region Restriction
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Deny",
          "Action": "*",
          "Resource": "*",
          "Condition": {
            "StringNotEquals": {
              "aws:RequestedRegion": ["us-east-1", "us-west-2"]
            }
          }
        }
      ]
    }
    ```
    
    ## Trust Policy Patterns
    
    ### Lambda Service Trust
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "lambda.amazonaws.com"
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }
    ```
    
    ### Cross-Account with External ID
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "AWS": "arn:aws:iam::111111111111:root"
          },
          "Action": "sts:AssumeRole",
          "Condition": {
            "StringEquals": {
              "sts:ExternalId": "unique-secret-id"
            }
          }
        }
      ]
    }
    ```
    
    ### Federated Identity (OIDC)
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
          },
          "Action": "sts:AssumeRoleWithWebIdentity",
          "Condition": {
            "StringEquals": {
              "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
            },
            "StringLike": {
              "token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:*"
            }
          }
        }
      ]
    }
    ```
    
    ## Resource-Based Policy Patterns
    
    ### S3 Bucket Policy
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "AllowCrossAccountAccess",
          "Effect": "Allow",
          "Principal": {
            "AWS": "arn:aws:iam::111111111111:role/CrossAccountRole"
          },
          "Action": ["s3:GetObject", "s3:ListBucket"],
          "Resource": [
            "arn:aws:s3:::my-bucket",
            "arn:aws:s3:::my-bucket/*"
          ]
        }
      ]
    }
    ```
    
    ### SQS Queue Policy
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "sns.amazonaws.com"
          },
          "Action": "sqs:SendMessage",
          "Resource": "arn:aws:sqs:us-east-1:123456789012:my-queue",
          "Condition": {
            "ArnEquals": {
              "aws:SourceArn": "arn:aws:sns:us-east-1:123456789012:my-topic"
            }
          }
        }
      ]
    }
    ```
    
    ## Permission Boundaries
    
    Permission boundaries limit the maximum permissions a role can have:
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "s3:*",
            "dynamodb:*",
            "lambda:*",
            "logs:*"
          ],
          "Resource": "*"
        },
        {
          "Effect": "Deny",
          "Action": [
            "iam:*",
            "organizations:*",
            "account:*"
          ],
          "Resource": "*"
        }
      ]
    }
    ```
    
    Apply to a role:
    
    ```bash
    aws iam put-role-permissions-boundary \
      --role-name DeveloperRole \
      --permissions-boundary arn:aws:iam::123456789012:policy/DeveloperBoundary
    ```
    
  • SKILL.md 6.9 KB
    ---
    name: iam
    description: AWS Identity and Access Management for users, roles, policies, and permissions. Use when creating IAM policies, configuring cross-account access, setting up service roles, troubleshooting permission errors, or managing access control.
    last_updated: "2026-01-07"
    doc_source: https://docs.aws.amazon.com/IAM/latest/UserGuide/
    ---
    
    # AWS IAM
    
    AWS Identity and Access Management (IAM) enables secure access control to AWS services and resources. IAM is foundational to AWS security—every AWS API call is authenticated and authorized through IAM.
    
    ## Table of Contents
    
    - [Core Concepts](#core-concepts)
    - [Common Patterns](#common-patterns)
    - [CLI Reference](#cli-reference)
    - [Best Practices](#best-practices)
    - [Troubleshooting](#troubleshooting)
    - [References](#references)
    
    ## Core Concepts
    
    ### Principals
    
    Entities that can make requests to AWS: IAM users, roles, federated users, and applications.
    
    ### Policies
    
    JSON documents defining permissions. Types:
    - **Identity-based**: Attached to users, groups, or roles
    - **Resource-based**: Attached to resources (S3 buckets, SQS queues)
    - **Permission boundaries**: Maximum permissions an identity can have
    - **Service control policies (SCPs)**: Organization-wide limits
    
    ### Roles
    
    Identities with permissions that can be assumed by trusted entities. No permanent credentials—uses temporary security tokens.
    
    ### Trust Relationships
    
    Define which principals can assume a role. Configured via the role's trust policy.
    
    ## Common Patterns
    
    ### Create a Service Role for Lambda
    
    **AWS CLI:**
    
    ```bash
    # Create the trust policy
    cat > trust-policy.json << 'EOF'
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": { "Service": "lambda.amazonaws.com" },
          "Action": "sts:AssumeRole"
        }
      ]
    }
    EOF
    
    # Create the role
    aws iam create-role \
      --role-name MyLambdaRole \
      --assume-role-policy-document file://trust-policy.json
    
    # Attach a managed policy
    aws iam attach-role-policy \
      --role-name MyLambdaRole \
      --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
    ```
    
    **boto3:**
    
    ```python
    import boto3
    import json
    
    iam = boto3.client('iam')
    
    trust_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {"Service": "lambda.amazonaws.com"},
                "Action": "sts:AssumeRole"
            }
        ]
    }
    
    # Create role
    iam.create_role(
        RoleName='MyLambdaRole',
        AssumeRolePolicyDocument=json.dumps(trust_policy)
    )
    
    # Attach managed policy
    iam.attach_role_policy(
        RoleName='MyLambdaRole',
        PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
    )
    ```
    
    ### Create Custom Policy with Least Privilege
    
    ```bash
    cat > policy.json << 'EOF'
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "dynamodb:GetItem",
            "dynamodb:PutItem",
            "dynamodb:Query"
          ],
          "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable"
        }
      ]
    }
    EOF
    
    aws iam create-policy \
      --policy-name MyDynamoDBPolicy \
      --policy-document file://policy.json
    ```
    
    ### Cross-Account Role Assumption
    
    ```bash
    # In Account B (trusted account), create role with trust for Account A
    cat > cross-account-trust.json << 'EOF'
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": { "AWS": "arn:aws:iam::111111111111:root" },
          "Action": "sts:AssumeRole",
          "Condition": {
            "StringEquals": { "sts:ExternalId": "unique-external-id" }
          }
        }
      ]
    }
    EOF
    
    # From Account A, assume the role
    aws sts assume-role \
      --role-arn arn:aws:iam::222222222222:role/CrossAccountRole \
      --role-session-name MySession \
      --external-id unique-external-id
    ```
    
    ## CLI Reference
    
    ### Essential Commands
    
    | Command | Description |
    |---------|-------------|
    | `aws iam create-role` | Create a new IAM role |
    | `aws iam create-policy` | Create a customer managed policy |
    | `aws iam attach-role-policy` | Attach a managed policy to a role |
    | `aws iam put-role-policy` | Add an inline policy to a role |
    | `aws iam get-role` | Get role details |
    | `aws iam list-roles` | List all roles |
    | `aws iam simulate-principal-policy` | Test policy permissions |
    | `aws sts assume-role` | Assume a role and get temporary credentials |
    | `aws sts get-caller-identity` | Get current identity |
    
    ### Useful Flags
    
    - `--query`: Filter output with JMESPath
    - `--output table`: Human-readable output
    - `--no-cli-pager`: Disable pager for scripting
    
    ## Best Practices
    
    ### Security
    
    - **Never use root account** for daily tasks
    - **Enable MFA** for all human users
    - **Use roles** instead of long-term access keys
    - **Apply least privilege** — grant only required permissions
    - **Use conditions** to restrict access by IP, time, or MFA
    - **Rotate credentials** regularly
    - **Use permission boundaries** for delegated administration
    
    ### Policy Design
    
    - Start with AWS managed policies, customize as needed
    - Use policy variables (`${aws:username}`) for dynamic policies
    - Prefer explicit denies for sensitive actions
    - Group related permissions logically
    
    ### Monitoring
    
    - Enable **CloudTrail** for API auditing
    - Use **IAM Access Analyzer** to identify overly permissive policies
    - Review **credential reports** regularly
    - Set up alerts for root account usage
    
    ## Troubleshooting
    
    ### Access Denied Errors
    
    **Symptom:** `AccessDeniedException` or `UnauthorizedAccess`
    
    **Debug steps:**
    1. Verify identity: `aws sts get-caller-identity`
    2. Check attached policies: `aws iam list-attached-role-policies --role-name MyRole`
    3. Simulate the action:
       ```bash
       aws iam simulate-principal-policy \
         --policy-source-arn arn:aws:iam::123456789012:role/MyRole \
         --action-names dynamodb:GetItem \
         --resource-arns arn:aws:dynamodb:us-east-1:123456789012:table/MyTable
       ```
    4. Check for explicit denies in SCPs or permission boundaries
    5. Verify resource-based policies allow the principal
    
    ### Role Cannot Be Assumed
    
    **Symptom:** `AccessDenied` when calling `AssumeRole`
    
    **Causes:**
    - Trust policy doesn't include the calling principal
    - Missing `sts:AssumeRole` permission on the caller
    - ExternalId mismatch (for cross-account roles)
    - Session duration exceeds maximum
    
    **Fix:** Review and update the role's trust relationship.
    
    ### Policy Size Limits
    
    - Managed policy: 6,144 characters
    - Inline policy: 2,048 characters (user), 10,240 characters (role/group)
    - Trust policy: 2,048 characters
    
    **Solution:** Use multiple policies, reference resources by prefix/wildcard, or use tags-based access control.
    
    ## References
    
    - [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/)
    - [IAM API Reference](https://docs.aws.amazon.com/IAM/latest/APIReference/)
    - [IAM CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/iam/)
    - [Policy Reference](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html)
    - [boto3 IAM](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html)
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related