AWS Compute Optimizer Recommendations Guide
Leverage AWS Compute Optimizer machine learning recommendations to right-size EC2, EBS, Lambda, and container resources.
AWS Compute Optimizer uses machine learning to analyze resource utilization and provide optimization recommendations for EC2, EBS, Lambda, and container workloads.
Enabling Compute Optimizer
Organization-Wide Enrollment
import boto3
compute_optimizer = boto3.client('compute-optimizer')
def enable_compute_optimizer_org():
# Opt in at organization level
response = compute_optimizer.update_enrollment_status(
status='Active',
includeMemberAccounts=True
)
return response
CloudFormation Setup
ComputeOptimizerRole:
Type: AWS::IAM::Role
Properties:
RoleName: ComputeOptimizerAccess
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: compute-optimizer.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/ComputeOptimizerServiceRolePolicy
EC2 Recommendations
Retrieve and Analyze
def get_ec2_recommendations():
response = compute_optimizer.get_ec2_instance_recommendations(
filters=[
{
'name': 'Finding',
'values': ['Overprovisioned', 'Underprovisioned']
}
]
)
recommendations = []
for rec in response['instanceRecommendations']:
current = rec['currentInstanceType']
for option in rec['recommendationOptions']:
projected_metrics = option.get('projectedUtilizationMetrics', [])
recommendations.append({
'instance_id': rec['instanceArn'].split('/')[-1],
'current_type': current,
'recommended_type': option['instanceType'],
'savings_opportunity': option.get('savingsOpportunity', {}),
'performance_risk': option.get('performanceRisk', 0),
'projected_cpu': next(
(m['value'] for m in projected_metrics if m['name'] == 'CPU'),
None
)
})
return recommendations
Automated Right-Sizing
def apply_ec2_recommendation(instance_id, new_type, dry_run=True):
ec2 = boto3.client('ec2')
# Get current state
instance = ec2.describe_instances(InstanceIds=[instance_id])
current_state = instance['Reservations'][0]['Instances'][0]['State']['Name']
if not dry_run:
# Stop instance
if current_state == 'running':
ec2.stop_instances(InstanceIds=[instance_id])
waiter = ec2.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[instance_id])
# Modify instance type
ec2.modify_instance_attribute(
InstanceId=instance_id,
InstanceType={'Value': new_type}
)
# Start instance
ec2.start_instances(InstanceIds=[instance_id])
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=[instance_id])
return {
'instance_id': instance_id,
'new_type': new_type,
'dry_run': dry_run
}
Lambda Recommendations
def get_lambda_recommendations():
response = compute_optimizer.get_lambda_function_recommendations()
recommendations = []
for rec in response['lambdaFunctionRecommendations']:
current_config = rec['currentMemorySize']
for option in rec.get('memorySizeRecommendationOptions', []):
recommendations.append({
'function_arn': rec['functionArn'],
'current_memory': current_config,
'recommended_memory': option['memorySize'],
'projected_cost': option.get('projectedUtilizationMetrics', []),
'savings_opportunity': option.get('savingsOpportunity', {})
})
return recommendations
def apply_lambda_recommendation(function_name, new_memory):
lambda_client = boto3.client('lambda')
lambda_client.update_function_configuration(
FunctionName=function_name,
MemorySize=new_memory
)
EBS Volume Recommendations
def get_ebs_recommendations():
response = compute_optimizer.get_ebs_volume_recommendations(
filters=[
{
'name': 'Finding',
'values': ['Optimized', 'NotOptimized']
}
]
)
recommendations = []
for rec in response['volumeRecommendations']:
current = rec['currentConfiguration']
for option in rec['volumeRecommendationOptions']:
config = option['configuration']
recommendations.append({
'volume_arn': rec['volumeArn'],
'current_type': current['volumeType'],
'current_size': current['volumeSize'],
'current_iops': current.get('volumeBaselineIOPS'),
'recommended_type': config['volumeType'],
'recommended_size': config['volumeSize'],
'recommended_iops': config.get('volumeBaselineIOPS'),
'savings': option.get('savingsOpportunity', {})
})
return recommendations
Reporting and Tracking
def generate_optimization_report():
report = {
'timestamp': datetime.now().isoformat(),
'ec2': get_ec2_recommendations(),
'lambda': get_lambda_recommendations(),
'ebs': get_ebs_recommendations()
}
total_savings = sum(
r.get('savings_opportunity', {}).get('estimatedMonthlySavings', {}).get('value', 0)
for category in ['ec2', 'lambda', 'ebs']
for r in report[category]
)
report['total_monthly_savings'] = total_savings
return report
Working with Warqline
We are a cloud engineering consultancy and an official AWS and Google Cloud partner. If you are running this in production and want a second pair of eyes, we scope work in a free 45-minute technical call: you describe what you are running and what worries you, and we tell you what we would look at first.
Conclusion
AWS Compute Optimizer provides ML-driven recommendations for resource optimization. Regularly review recommendations, implement changes systematically, and track savings over time.