ユーザー、ロール、ポリシー、および権限に関するAWS Identity and Access Management(IAM)を管理します。IAMポリシーの作成、アカウント間のアクセス設定、サービスロールの設定、権限エラーのトラブルシューティングを行い、最小権限の原則に基づくセキュリティを徹底します。
...すべて拡張しますAWSIAM
AWS Identity and Access Management(IAM )は、AWSのサービスおよびリソースに対する安全なアクセス制御を実現します。IAM はAWSセキュリティの基盤であり、すべてのAWS API呼び出しはIAM を通じて認証および承認されます。
目次
- 基本概念
- 一般的なパターン
- CLI リファレンス
- ベストプラクティス
- トラブルシューティング
- 参考資料
中核となる概念
プリンシパル
AWS にリクエストを送信できるエンティティ:IAM ユーザー、ロール、フェデレーションユーザー、およびアプリケーション。
ポリシー
権限を定義するJSONドキュメント。種類:
- IDベース:ユーザー、グループ、またはロールに紐付けられる
- リソースベース:リソース(S3バケット、SQSキュー)に紐付けられる
- 権限の境界:1つのIDが持つことができる権限の上限
- サービス制御ポリシー(SCP):組織全体での制限
ロール
信頼されたエンティティが引き継ぐことができる権限を持つID。永続的な認証情報はなく、一時的なセキュリティトークンを使用する。
信頼関係
どのプリンシパルがロールを引き受けられるかを定義します。ロールの信頼ポリシーを通じて構成されます。
一般的なパターン
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 |
現在のIDを取得する |
便利なフラグ
--query: JMESPath を使用して出力をフィルタリングする--output table: 人間が読みやすい形式で出力--no-cli-pager: スクリプト実行時にページャーを無効化
ベストプラクティス
セキュリティ
- 日常業務ではrootアカウントを絶対に使用しない
- すべてのユーザーに対して多要素認証(MFA)を有効にする
- 長期アクセスキーの代わりにロールを使用する
- 最小権限の原則を適用する— 必要な権限のみを付与する
- 条件を設定して、IPアドレス、時間帯、またはMFAによるアクセスを制限する
- 認証情報を定期的に更新する
- 委任管理には権限の境界を設定する
ポリシーの設計
- まずはAWSマネージドポリシーから始め、必要に応じてカスタマイズする
- 動的なポリシーにはポリシー変数(
${aws:username})を使用する - 機密性の高いアクションに対しては、明示的な拒否を優先する
- 関連する権限を論理的にグループ化する
監視
- API監査のためにCloudTrailを有効にする
- IAM のAccess Analyzerを使用して、許可範囲が広すぎるポリシーを特定する
- 認証情報レポートを定期的に確認する
- root アカウントの使用状況に関するアラートを設定する
トラブルシューティング
「アクセス拒否」エラー
症状: AccessDeniedExceptionまたはUnauthorizedAccess
デバッグ手順:
- IDの確認:
aws sts get-caller-identity - 関連付けられたポリシーを確認する:
awsiam list-attached-role-policies --role-name MyRole - アクションのシミュレーション:
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 - SCP や権限境界に明示的な拒否設定がないか確認する
- リソースベースのポリシーがプリンシパルにアクセス権を許可しているか確認する
ロールの引き受けができない
症状: AssumeRoleの呼び出し時にAccessDeniedが発生する
原因:
- 信頼ポリシーに呼び出し元のプリンシパルが含まれていない
- 呼び出し元プリンシパルに
sts:AssumeRole権限がない - ExternalId の不一致(アカウントをまたぐロールの場合)
- セッションの有効期間が最大値を超えている
解決策:ロールの信頼関係を再確認し、更新してください。
ポリシーのサイズ制限
- 管理対象ポリシー:6,144 文字
- インライン ポリシー:2,048 文字(ユーザー)、10,240 文字(ロール/グループ)
- 信頼ポリシー: 2,048 文字
解決策:複数のポリシーを使用するか、プレフィックスやワイルドカードでリソースを参照するか、タグベースのアクセス制御を使用してください。
参考文献
- IAM ユーザーガイド
- IAM API リファレンス
- IAM CLI リファレンス
- ポリシーリファレンス
- boto3IAM
---
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)
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
コピー





家
