选项

管理 AWS 身份与访问管理(IAM)中的用户、角色、策略和权限。创建 IAM 策略、配置跨账户访问、设置服务角色、排查权限错误,并实施最小权限原则。

...展开全部
34
更新时间 2026-09-21

AWSIAM

AWS 身份与访问管理(IAM )可对 AWS 服务和资源实施安全的访问控制。IAM 是 AWS 安全的基础——每次 AWS API 调用都会通过IAM 进行身份验证和授权。

目录

  • 核心概念
  • 常见模式
  • CLI 参考
  • 最佳实践
  • 故障排除
  • 参考资料

核心概念

主体

可以向 AWS 发送请求的实体:IAM 用户、角色、联合用户和应用程序。

策略

定义权限的 JSON 文档。类型:

  • 基于身份的:关联到用户、组或角色
  • 基于资源的策略:关联到资源(S3 存储桶、SQS 队列)
  • 权限边界:身份可拥有的最大权限范围
  • 服务控制策略(SCP):全组织范围的限制

角色

其权限可由受信任实体承接的身份。不使用永久凭证——而是使用临时安全令牌。

信任关系

定义哪些主体可以承担某个角色。通过角色的信任策略进行配置。

常见模式

为 Lambda 创建服务角色

AWS CLI:

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

# 创建角色
aws iam create-role \
  --role-name MyLambdaRole \
  --assume-role-policy-document file://trust-policy.json

# 关联托管策略
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"
        }
    ]
}

# 创建角色iam.create_role(
    RoleName='MyLambdaRole',
    AssumeRolePolicyDocument=json.dumps(trust_policy)
)

# 关联托管策略
iam.attach_role_policy(
    RoleName='MyLambdaRole',
    PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
)

创建遵循最小权限原则的自定义策略

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

跨账户角色承接

# 在账户 B(受信任账户)中,创建一个信任账户 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

# 从账户 A 接管该角色
aws sts assume-role \
  --role-arn arn:aws:iam::222222222222:role/CrossAccountRole \
  --role-session-name MySession \
  --external-id unique-external-id

CLI 参考

常用命令

命令 描述
awsiam create-role 创建新的IAM 角色
awsiam create-policy 创建客户管理策略
awsiam attach-role-policy 将托管策略关联到角色
awsiam put-role-policy 向角色添加内联策略
awsiam get-role 获取角色详细信息
awsiam list-roles 列出所有角色
awsiam simulate-principal-policy 测试策略权限
aws sts assume-role 承接角色并获取临时凭证
aws sts get-caller-identity 获取当前身份

有用的标志

  • --query:使用 JMESPath 过滤输出
  • --output table:以人类可读格式输出
  • --no-cli-pager:禁用脚本模式下的分页器

最佳实践

安全性

  • 切勿使用 root 账户执行日常任务
  • 为所有人工用户启用多因素认证
  • 使用角色代替长期访问密钥
  • 遵循最小权限原则——仅授予必要的权限
  • 使用条件规则限制基于 IP 地址、时间或多因素身份验证的访问
  • 定期轮换凭据
  • 在委托管理中使用权限边界

策略设计

  • 从 AWS 托管策略开始,根据需要进行自定义
  • 使用策略变量(${aws:username})来创建动态策略
  • 对敏感操作,优先采用显式拒绝策略
  • 按逻辑将相关权限分组

监控

  • 启用CloudTrail进行 API 审计
  • 使用IAM 访问分析器来识别权限过于宽松的策略
  • 定期审查凭据报告
  • 为 root 账户的使用设置警报

故障排除

“访问被拒绝”错误

症状: AccessDeniedException或UnauthorizedAccess

调试步骤:

  1. 验证身份:aws sts get-caller-identity
  2. 检查关联策略:awsiam list-attached-role-policies --role-name MyRole
  3. 模拟操作:
    awsiam 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. 检查 SCP 或权限边界中是否存在显式拒绝
  5. 验证基于资源的策略是否允许该主体

无法承接角色

症状:调用AssumeRole时出现AccessDenied错误

原因:

  • 信任策略中未包含调用主体
  • 调用方缺少sts:AssumeRole权限
  • ExternalId 不匹配(适用于跨账户角色)
  • 会话时长超过最大限制

解决方法:检查并更新角色的信任关系。

策略大小限制

  • 托管策略:6,144 个字符
  • 内联策略:2,048 个字符(用户),10,240 个字符(角色/组)
  • 信任策略:2,048 个字符

解决方案:使用多个策略,通过前缀/通配符引用资源,或使用基于标签的访问控制。

参考资料

  • IAM 用户指南
  • IAM API 参考
  • IAM CLI 参考
  • 策略参考
  • boto3IAM
在 GitHub 上查看
---
name: iam
description: Manage AWS Identity and Access Management for users, roles, policies, and permissions. Create IAM policies, configure cross-account access, set up service roles, troubleshoot permission errors, and enforce least-privilege security.
---

# 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)

所有文件

3 个文件

安装 iam

下载技能文件并将其解压到 .claude/skills/ 目录中。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/iam # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ Claude 会自动检测并使用该技能

相关技能

gmgn-portfolio
更新时间 2026-07-01
device-integrity
更新时间 2026-06-29
zeroize-audit
更新时间 2026-07-01
flutter-use-http-package
更新时间 2026-06-30
OR