Chapter 08: IAM Integration with Other AWS Services
Learn IAM integration with EC2, Lambda, S3 and other AWS services and permission management
Haiyue
14min
Chapter 8: IAM Integration with Other AWS Services
Learning Objectives
- Master IAM integration configuration with EC2 instances
- Learn Lambda function permission management
- Understand S3 bucket policy configuration
- Master cross-service permission management
- Implement secure inter-service communication
Service Integration Architecture Diagram
🔄 正在渲染 Mermaid 图表...
8.1 IAM Integration with EC2
8.1.1 EC2 Instance Role Configuration
import boto3
import json
from datetime import datetime
def configure_ec2_iam_integration():
"""
Configure EC2 integration with IAM
"""
class EC2IAMIntegration:
def __init__(self):
self.iam = boto3.client('iam')
self.ec2 = boto3.client('ec2')
self.sts = boto3.client('sts')
def create_ec2_service_role(self, role_name, permissions):
"""Create EC2 service role"""
# EC2 trust policy
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
try:
# Create role
role_response = self.iam.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description=f'Service role for EC2 instances: {role_name}',
Tags=[
{'Key': 'Service', 'Value': 'EC2'},
{'Key': 'ManagedBy', 'Value': 'IAM-Automation'},
{'Key': 'CreatedDate', 'Value': datetime.now().strftime('%Y-%m-%d')}
]
)
role_arn = role_response['Role']['Arn']
print(f"✅ EC2 role created successfully: {role_arn}")
# Attach permission policies
for permission in permissions:
if permission['type'] == 'managed':
self.iam.attach_role_policy(
RoleName=role_name,
PolicyArn=permission['arn']
)
elif permission['type'] == 'inline':
self.iam.put_role_policy(
RoleName=role_name,
PolicyName=permission['name'],
PolicyDocument=json.dumps(permission['document'])
)
# Create instance profile
self.iam.create_instance_profile(
InstanceProfileName=role_name
)
# Add role to instance profile
self.iam.add_role_to_instance_profile(
InstanceProfileName=role_name,
RoleName=role_name
)
print(f"✅ Instance profile created successfully: {role_name}")
return {
'role_arn': role_arn,
'instance_profile_name': role_name
}
except Exception as e:
print(f"❌ Failed to create EC2 role: {str(e)}")
return None
def create_web_server_role(self):
"""Create web server role"""
permissions = [
{
'type': 'managed',
'arn': 'arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy'
},
{
'type': 'inline',
'name': 'WebServerCustomPolicy',
'document': {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-web-content/*"
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameter",
"ssm:GetParameters",
"ssm:GetParametersByPath"
],
"Resource": "arn:aws:ssm:*:*:parameter/webserver/*"
},
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": "arn:aws:secretsmanager:*:*:secret:webserver/*"
}
]
}
}
]
return self.create_ec2_service_role("WebServerRole", permissions)
return EC2IAMIntegration()
# Demonstrate EC2 IAM integration
ec2_iam = configure_ec2_iam_integration()
# Create web server role
web_role = ec2_iam.create_web_server_role()
print("\n📋 EC2 IAM Integration Configuration Complete:")
print(" ✅ Web server role created")
print(" ✅ Instance profile configured")
8.2 IAM Integration with Lambda
8.2.1 Lambda Execution Role Management
def configure_lambda_iam_integration():
"""
Configure Lambda integration with IAM
"""
class LambdaIAMIntegration:
def __init__(self):
self.iam = boto3.client('iam')
self.lambda_client = boto3.client('lambda')
def create_lambda_execution_role(self, function_name, permissions_config):
"""Create Lambda execution role"""
role_name = f"Lambda-{function_name}-ExecutionRole"
# Lambda trust policy
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
try:
# Create role
role_response = self.iam.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description=f'Execution role for Lambda function: {function_name}'
)
role_arn = role_response['Role']['Arn']
print(f"✅ Lambda execution role created successfully: {role_arn}")
# Attach basic execution policy
self.iam.attach_role_policy(
RoleName=role_name,
PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
)
# Add additional permissions based on configuration
if permissions_config.get('vpc_access'):
self.iam.attach_role_policy(
RoleName=role_name,
PolicyArn='arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole'
)
# Create custom permission policy
if permissions_config.get('custom_permissions'):
custom_policy = {
"Version": "2012-10-17",
"Statement": permissions_config['custom_permissions']
}
policy_response = self.iam.create_policy(
PolicyName=f'Lambda-{function_name}-CustomPolicy',
PolicyDocument=json.dumps(custom_policy),
Description=f'Custom permissions for {function_name}'
)
self.iam.attach_role_policy(
RoleName=role_name,
PolicyArn=policy_response['Policy']['Arn']
)
return role_arn
except Exception as e:
print(f"❌ Failed to create Lambda role: {str(e)}")
return None
return LambdaIAMIntegration()
# Demonstrate Lambda IAM integration
lambda_iam = configure_lambda_iam_integration()
print("\n📋 Lambda IAM Integration Configuration Complete:")
print(" ✅ API handler role created")
print(" ✅ Data processor role created")
print(" ✅ Scheduled task role created")
8.3 IAM Integration with S3
8.3.1 S3 Bucket Policy Configuration
def configure_s3_iam_integration():
"""
Configure S3 integration with IAM
"""
class S3IAMIntegration:
def __init__(self):
self.s3 = boto3.client('s3')
self.iam = boto3.client('iam')
def create_bucket_with_policy(self, bucket_name, bucket_policy_config):
"""Create S3 bucket with IAM policy"""
try:
# Create bucket
if boto3.Session().region_name != 'us-east-1':
self.s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={
'LocationConstraint': boto3.Session().region_name
}
)
else:
self.s3.create_bucket(Bucket=bucket_name)
print(f"✅ S3 bucket created successfully: {bucket_name}")
# Configure bucket policy
bucket_policy = self._generate_bucket_policy(bucket_name, bucket_policy_config)
self.s3.put_bucket_policy(
Bucket=bucket_name,
Policy=json.dumps(bucket_policy)
)
print(f"✅ Bucket policy configured successfully")
return bucket_name
except Exception as e:
print(f"❌ Failed to create S3 bucket: {str(e)}")
return None
def _generate_bucket_policy(self, bucket_name, config):
"""Generate bucket policy"""
statements = []
# Deny non-SSL requests
if config.get('require_ssl', True):
statements.append({
"Sid": "DenyInsecureConnections",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
f"arn:aws:s3:::{bucket_name}",
f"arn:aws:s3:::{bucket_name}/*"
],
"Condition": {
"Bool": {
"aws:SecureTransport": "false"
}
}
})
return {
"Version": "2012-10-17",
"Statement": statements
}
return S3IAMIntegration()
# Demonstrate S3 IAM integration
s3_iam = configure_s3_iam_integration()
print("\n📋 S3 IAM Integration Configuration:")
print(" ✅ Bucket policy templates prepared")
print(" ✅ Encryption and logging configuration prepared")
print(" ✅ Cross-account access policies prepared")
Summary
This chapter introduced IAM integration with core AWS services:
- EC2 Integration: Instance roles, permission configuration, and service-specific policies
- Lambda Integration: Execution roles, custom permissions, and function deployment
- S3 Integration: Bucket policies, encryption configuration, and access control
- Best Practices: Least privilege, security configuration, and monitoring audit
Through service integration, you can:
- Implement secure cross-service communication
- Configure fine-grained permission control
- Establish complete security policy system
- Implement automated permission management
In the next chapter, we will learn federated identity and single sign-on configuration.