選項

管理 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 帳戶執行日常任務
  • 為所有人類使用者啟用多因素驗證 (MFA)
  • 使用角色取代長期存取金鑰
  • 遵循最小權限原則— 僅授予必要的權限
  • 使用條件來根據 IP 位址、時間或多因素驗證 (MFA) 限制存取權限
  • 定期輪替憑證
  • 針對委派管理使用權限邊界

政策設計

  • 從 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