Chapter 01: AWS IAM Basic Concepts
9/1/25About 6 min
Chapter 01: AWS IAM Basic Concepts
Learning Objectives
- Understand what AWS IAM is and its core functions
- Master the basic components and concepts of IAM
- Understand the position of IAM in the AWS security architecture
- Understand the difference between authentication and authorization
Knowledge Points
What is AWS IAM
AWS Identity and Access Management (IAM) is a web service that helps you securely control access to AWS resources. IAM allows you to control who can be authenticated (logged in) and authorized (have permissions) to use resources.
Core Components of IAM
IAM Component Details
Component | Purpose | Features | Use Case |
---|---|---|---|
Users | Represents a person or application | Permanent credentials, long-term access | Developers, system administrators |
Groups | A collection of users | Simplifies permission management | Department, team permission management |
Roles | An identity that can be assumed | Temporary credentials, high security | Inter-service calls, cross-account access |
Policies | Documents that define permissions | JSON format, fine-grained control | Permission definition and management |
Authentication vs. Authorization
Example Code
IAM Basic Concepts Example
import boto3
import json
from datetime import datetime
# Initialize the IAM client
iam_client = boto3.client('iam')
def demonstrate_iam_concepts():
"""
Demonstrate basic IAM concepts and components
"""
print("=== AWS IAM Basic Concepts Demonstration ===")
# 1. List users in the current account
print("\n1. IAM users in the current account:")
try:
users_response = iam_client.list_users()
for user in users_response['Users']:
print(f" - Username: {user['UserName']}")
print(f" Creation time: {user['CreateDate']}")
print(f" ARN: {user['Arn']}")
except Exception as e:
print(f" Failed to get user list: {e}")
# 2. List user groups
print("\n2. IAM groups in the current account:")
try:
groups_response = iam_client.list_groups()
for group in groups_response['Groups']:
print(f" - Group name: {group['GroupName']}")
print(f" Creation time: {group['CreateDate']}")
print(f" ARN: {group['Arn']}")
except Exception as e:
print(f" Failed to get group list: {e}")
# 3. List roles
print("\n3. IAM roles in the current account:")
try:
roles_response = iam_client.list_roles(MaxItems=5) # Limit the number displayed
for role in roles_response['Roles']:
print(f" - Role name: {role['RoleName']}")
print(f" Creation time: {role['CreateDate']}")
print(f" Description: {role.get('Description', 'No description')}")
except Exception as e:
print(f" Failed to get role list: {e}")
# 4. List policies (only show customer-managed policies)
print("\n4. Customer-managed policies in the current account:")
try:
policies_response = iam_client.list_policies(
Scope='Local', # Only show policies created by the customer
MaxItems=5
)
for policy in policies_response['Policies']:
print(f" - Policy name: {policy['PolicyName']}")
print(f" ARN: {policy['Arn']}")
print(f" Description: {policy.get('Description', 'No description')}")
except Exception as e:
print(f" Failed to get policy list: {e}")
def analyze_iam_structure():
"""
Analyze IAM structure and relationships
"""
print("\n=== IAM Structure Analysis ===")
try:
# Get account summary
summary = iam_client.get_account_summary()
summary_map = summary['SummaryMap']
print("\nAccount IAM resource statistics:")
print(f" - Number of users: {summary_map.get('Users', 0)}")
print(f" - Number of groups: {summary_map.get('Groups', 0)}")
print(f" - Number of roles: {summary_map.get('Roles', 0)}")
print(f" - Number of policies: {summary_map.get('Policies', 0)}")
print(f" - Customer-managed policies: {summary_map.get('PolicyVersionsInUse', 0)}")
# Analyze password policy
try:
password_policy = iam_client.get_account_password_policy()
policy = password_policy['PasswordPolicy']
print("\nAccount password policy:")
print(f" - Minimum length: {policy.get('MinimumPasswordLength', 'Not set')}")
print(f" - Requires uppercase letters: {policy.get('RequireUppercaseCharacters', False)}")
print(f" - Requires lowercase letters: {policy.get('RequireLowercaseCharacters', False)}")
print(f" - Requires numbers: {policy.get('RequireNumbers', False)}")
print(f" - Requires symbols: {policy.get('RequireSymbols', False)}")
print(f" - Password expiration days: {policy.get('MaxPasswordAge', 'Does not expire')}")
except iam_client.exceptions.NoSuchEntityException:
print("\nAccount password policy: No custom password policy set")
except Exception as e:
print(f"Failed to get account summary: {e}")
def demonstrate_policy_evaluation():
"""
Demonstrate IAM policy evaluation logic
"""
print("\n=== IAM Policy Evaluation Logic ===")
# Basic principles of policy evaluation
evaluation_rules = {
"Default Deny": "By default, all requests are denied",
"Explicit Allow": "An explicit Allow statement can override the default deny",
"Explicit Deny": "An explicit Deny statement has the highest priority",
"Policy Types": "Combined evaluation of identity policies, resource policies, permission boundaries, SCPs, etc."
}
print("\nPolicy evaluation principles:")
for rule, description in evaluation_rules.items():
print(f" - {rule}: {description}")
# Simulate the policy evaluation process
print("\nPolicy evaluation process:")
print(" 1. Collect all applicable policies")
print(" 2. Check for an explicit deny -> if so, deny immediately")
print(" 3. Check for an explicit allow -> if so, allow")
print(" 4. Default deny -> deny if not explicitly allowed")
if __name__ == "__main__":
# Run the demonstration functions
demonstrate_iam_concepts()
analyze_iam_structure()
demonstrate_policy_evaluation()
IAM Permission Checker Tool
import boto3
import json
from botocore.exceptions import ClientError
class IAMPermissionChecker:
"""
IAM permission checker tool class
"""
def __init__(self):
self.iam_client = boto3.client('iam')
self.sts_client = boto3.client('sts')
def check_current_identity(self):
"""
Check the current identity information
"""
try:
identity = self.sts_client.get_caller_identity()
print("Current identity information:")
print(f" - Account ID: {identity['Account']}")
print(f" - User/Role ARN: {identity['Arn']}")
print(f" - User ID: {identity['UserId']}")
return identity
except Exception as e:
print(f"Failed to get identity information: {e}")
return None
def check_user_permissions(self, username):
"""
Check the permissions of a specified user
"""
print(f"\nChecking permissions for user '{username}':")
try:
# Get user information
user = self.iam_client.get_user(UserName=username)
print(f" User ARN: {user['User']['Arn']}")
# Get policies directly attached to the user
attached_policies = self.iam_client.list_attached_user_policies(
UserName=username
)
print(f" Number of directly attached managed policies: {len(attached_policies['AttachedPolicies'])}")
for policy in attached_policies['AttachedPolicies']:
print(f" - {policy['PolicyName']} ({policy['PolicyArn']})")
# Get the user's inline policies
inline_policies = self.iam_client.list_user_policies(UserName=username)
print(f" Number of inline policies: {len(inline_policies['PolicyNames'])}")
for policy_name in inline_policies['PolicyNames']:
print(f" - {policy_name}")
# Get the groups the user belongs to
groups = self.iam_client.get_groups_for_user(UserName=username)
print(f" Number of groups: {len(groups['Groups'])}")
for group in groups['Groups']:
print(f" - {group['GroupName']}")
self._check_group_permissions(group['GroupName'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntity':
print(f" User '{username}' does not exist")
else:
print(f" Failed to check user permissions: {e}")
def _check_group_permissions(self, group_name):
"""
Check group permissions (private method)
"""
try:
# Get policies attached to the group
attached_policies = self.iam_client.list_attached_group_policies(
GroupName=group_name
)
if attached_policies['AttachedPolicies']:
print(f" Managed policies for group '{group_name}':")
for policy in attached_policies['AttachedPolicies']:
print(f" - {policy['PolicyName']}")
# Get the group's inline policies
inline_policies = self.iam_client.list_group_policies(GroupName=group_name)
if inline_policies['PolicyNames']:
print(f" Inline policies for group '{group_name}':")
for policy_name in inline_policies['PolicyNames']:
print(f" - {policy_name}")
except Exception as e:
print(f" Failed to check permissions for group '{group_name}': {e}")
def simulate_policy(self, principal_arn, action_names, resource_arns):
"""
Simulate policy execution
"""
print(f"\nSimulating policy execution:")
print(f" Principal: {principal_arn}")
print(f" Actions: {', '.join(action_names)}")
print(f" Resources: {', '.join(resource_arns)}")
try:
response = self.iam_client.simulate_principal_policy(
PolicySourceArn=principal_arn,
ActionNames=action_names,
ResourceArns=resource_arns
)
print(f"\nSimulation results:")
for result in response['EvaluationResults']:
action = result['EvalActionName']
decision = result['EvalDecision']
resource = result['EvalResourceName']
print(f" Action: {action}")
print(f" Resource: {resource}")
print(f" Decision: {decision}")
if 'MatchedStatements' in result:
print(f" Number of matched statements: {len(result['MatchedStatements'])}")
print()
except Exception as e:
print(f" Policy simulation failed: {e}")
# Example usage
if __name__ == "__main__":
checker = IAMPermissionChecker()
# Check the current identity
identity = checker.check_current_identity()
# To check a specific user, uncomment and replace the username
# checker.check_user_permissions("your-username")
# Policy simulation example (requires actual ARNs)
# checker.simulate_policy(
# principal_arn="arn:aws:iam::123456789012:user/testuser",
# action_names=["s3:GetObject"],
# resource_arns=["arn:aws:s3:::my-bucket/*"]
# )
IAM's Role in AWS Security Architecture
Summary of Core IAM Concepts
Key Functions of IAM
- Centralized Access Control: Uniformly manage access permissions for all AWS resources
- Fine-grained Permissions: Precisely control specific operations on specific resources
- Temporary Credentials: Provide secure temporary access through roles
- Federated Identity: Integrate with existing identity systems
- Audit Trail: Complete access logging
Important Concept Distinctions
- User vs. Role: Users have permanent credentials, roles use temporary credentials
- Managed Policy vs. Inline Policy: Managed policies are reusable, inline policies are embedded in a specific entity
- Identity Policy vs. Resource Policy: Identity policies are attached to identities, resource policies are attached to resources
- Allow vs. Deny: Deny always takes precedence over allow
Best Practice Principles
Principle | Description | Implementation Method |
---|---|---|
Least Privilege | Grant only the minimum permissions required to complete a task | Regularly review and clean up permissions |
Separation of Duties | Assign different permissions to different roles | Create specialized roles and groups |
Strong Authentication | Use strong passwords and MFA | Enable password policies and MFA |
Regular Rotation | Regularly rotate access keys | Set up an access key rotation policy |
Monitoring and Auditing | Log and monitor all access activities | Enable CloudTrail and CloudWatch |
Key Takeaways
IAM is the core foundation of AWS security. Correctly understanding and using IAM components is key to building a secure cloud architecture. Mastering the relationships between users, groups, roles, and policies, as well as the difference between authentication and authorization, is fundamental to in-depth learning of IAM.