Amazon EC2 - Interview Preparation
Total Questions: 252 Levels: Core Fundamentals (100), Intermediate (120), Advanced (80)
Table of Contents
1. Core Fundamentals
Q1: What is Amazon EC2 and what are the different instance types?
Technical Answer: Amazon EC2 provides resizable compute capacity with various instance types optimized for different workloads.
Instance Categories:
| Category | Use Case | Examples |
|---|---|---|
| General | Web servers, small DB | t3, m6i, m7g |
| Compute | HPC, batch processing | c6i, c7g |
| Memory | In-memory DB, caching | r6i, x2idn |
| Storage | NoSQL, data warehousing | i4i, d3en |
| GPU | ML inference, graphics | g5, p4d |
| Burstable | Variable workloads | t3, t4g |
Launching EC2:
import boto3
ec2 = boto3.client('ec2')
response = ec2.run_instances(
ImageId='ami-0123456789abcdef0',
MinCount=1,
MaxCount=1,
InstanceType='t3.medium',
KeyName='my-key-pair',
SecurityGroupIds=['sg-123456'],
SubnetId='subnet-123456',
IamInstanceProfile={'Name': 'EC2-SSM-Role'},
UserData='''#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "Hello from EC2" > /var/www/html/index.html
''',
BlockDeviceMappings=[{
'DeviceName': '/dev/xvda',
'Ebs': {
'VolumeSize': 20,
'VolumeType': 'gp3',
'Iops': 3000,
'Encrypted': True
}
}],
MetadataOptions={
'HttpTokens': 'required', # IMDSv2
'HttpEndpoint': 'enabled'
},
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': 'web-server-01'}]
}]
)
🔍 Interviewer Notes: Testing compute options and instance selection.
❌ Common Mistakes:
- Using wrong instance family
- Not using Graviton for price/performance
- Not enabling EBS optimization
Q2: How do you manage EC2 security?
Technical Answer: EC2 security involves security groups, IAM roles, and system hardening.
Security Groups:
import boto3
ec2 = boto3.client('ec2')
# Create security group
sg = ec2.create_security_group(
GroupName='web-server-sg',
Description='Security group for web servers',
VpcId='vpc-123456'
)
# Add inbound rules
ec2.authorize_security_group_ingress(
GroupId=sg['GroupId'],
IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 80,
'ToPort': 80,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
},
{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
},
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'UserIdGroupPairs': [{'GroupId': 'sg-bastion'}]
}
]
)
Least Privilege IAM Role:
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3ReadSpecificBucket",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::app-assets-bucket",
"arn:aws:s3:::app-assets-bucket/*"
]
},
{
"Sid": "CloudWatchLogs",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:log-group:/ec2/web-servers:*"
},
{
"Sid": "SSM",
"Effect": "Allow",
"Action": [
"ssm:UpdateInstanceInformation",
"ssmmessages:*",
"ec2messages:*"
],
"Resource": "*"
}
]
}
🔍 Interviewer Notes: Testing security best practices.
❌ Common Mistakes:
- Opening 0.0.0.0/0 for SSH
- Using long-term access keys
- Not using Systems Manager instead of SSH
Q3: How do you implement Auto Scaling for EC2?
Technical Answer: Auto Scaling automatically adjusts EC2 capacity based on demand.
Launch Template and ASG:
import boto3
ec2 = boto3.client('ec2')
autoscaling = boto3.client('autoscaling')
# Create launch template
lt_response = ec2.create_launch_template(
LaunchTemplateName='web-server-template',
LaunchTemplateData={
'ImageId': 'ami-0123456789abcdef0',
'InstanceType': 't3.medium',
'KeyName': 'my-key',
'SecurityGroupIds': ['sg-123'],
'IamInstanceProfile': {'Name': 'EC2-Role'},
'BlockDeviceMappings': [{
'DeviceName': '/dev/xvda',
'Ebs': {'VolumeSize': 20, 'VolumeType': 'gp3', 'Encrypted': True}
}],
'MetadataOptions': {'HttpTokens': 'required'}
}
)
# Create Auto Scaling Group
asg = autoscaling.create_auto_scaling_group(
AutoScalingGroupName='web-servers-asg',
LaunchTemplate={
'LaunchTemplateId': lt_response['LaunchTemplate']['LaunchTemplateId'],
'Version': '$Latest'
},
MinSize=2,
MaxSize=10,
DesiredCapacity=2,
VPCZoneIdentifier='subnet-123,subnet-456',
TargetGroupARNs=['arn:aws:elasticloadbalancing:...:targetgroup/web/...'],
HealthCheckType='ELB',
HealthCheckGracePeriod=300
)
# Target tracking scaling
autoscaling.put_scaling_policy(
AutoScalingGroupName='web-servers-asg',
PolicyName='cpu-target-tracking',
PolicyType='TargetTrackingScaling',
TargetTrackingConfiguration={
'PredefinedMetricSpecification': {
'PredefinedMetricType': 'ASGAverageCPUUtilization'
},
'TargetValue': 50.0,
'ScaleOutCooldown': 300,
'ScaleInCooldown': 600
}
)
Predictive Scaling:
autoscaling.put_scaling_policy(
AutoScalingGroupName='web-servers-asg',
PolicyName='predictive-scaling',
PolicyType='PredictiveScaling',
PredictiveScalingConfiguration={
'MetricSpecification': {
'TargetValue': 50.0,
'PredefinedLoadMetricSpecification': {
'PredefinedMetricType': 'ASGTotalCPUUtilization'
},
'PredefinedScalingMetricSpecification': {
'PredefinedMetricType': 'ASGAverageCPUUtilization'
}
},
'Mode': 'ForecastAndScale',
'SchedulingBufferTime': 10
}
)
🔍 Interviewer Notes: Testing scaling strategies and capacity management.
❌ Common Mistakes:
- Not using cooldown periods
- Scaling too aggressively
- Not testing scale-in scenarios
Q4: What are EBS volume types and when to use each?
Technical Answer:
| Volume Type | Use Case | Max IOPS | Max Throughput |
|---|---|---|---|
| gp3 | General purpose | 16,000 | 1,000 MB/s |
| gp2 | Legacy general purpose | 16,000 | 250 MB/s |
| io2 | Critical apps, databases | 256,000 | 4,000 MB/s |
| io1 | Legacy high performance | 64,000 | 1,000 MB/s |
| st1 | Big data, data warehouses | 500 | 500 MB/s |
| sc1 | Cold data, infrequent access | 250 | 250 MB/s |
Creating EBS Volumes:
import boto3
ec2 = boto3.client('ec2')
# Create gp3 volume
volume = ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='gp3',
Iops=3000, # gp3: 3,000-16,000 IOPS
Throughput=125, # gp3: 125-1,000 MB/s
Encrypted=True,
KmsKeyId='arn:aws:kms:us-east-1:123456789:key/123',
TagSpecifications=[{
'ResourceType': 'volume',
'Tags': [{'Key': 'Name', 'Value': 'data-volume'}]
}]
)
# Attach to instance
ec2.attach_volume(
VolumeId=volume['VolumeId'],
InstanceId='i-123456789',
Device='/dev/sdf'
)
🔍 Interviewer Notes: Testing storage optimization.
Q5: How do you implement EC2 Spot Instances?
Technical Answer: Spot Instances use spare EC2 capacity at up to 90% discount.
Spot Fleet:
import boto3
ec2 = boto3.client('ec2')
spot_fleet = ec2.request_spot_fleet(
SpotFleetRequestConfig={
'IamFleetRole': 'arn:aws:iam::123456789:role/aws-ec2-spot-fleet-tagging-role',
'AllocationStrategy': 'capacityOptimized',
'TargetCapacity': 10,
'SpotPrice': '0.50',
'LaunchTemplateConfigs': [{
'LaunchTemplateSpecification': {
'LaunchTemplateId': 'lt-123',
'Version': '1'
},
'Overrides': [
{'InstanceType': 'm5.large', 'SubnetId': 'subnet-123'},
{'InstanceType': 'm5a.large', 'SubnetId': 'subnet-123'},
{'InstanceType': 'm6i.large', 'SubnetId': 'subnet-123'}
]
}]
}
)
Handling Interruptions:
#!/usr/bin/env python3
import requests
import time
import sys
METADATA_URL = 'http://169.254.169.254/latest/meta-data/spot/instance-action'
def check_interruption():
try:
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '300'},
timeout=2
).text
response = requests.get(
METADATA_URL,
headers={'X-aws-ec2-metadata-token': token},
timeout=2
)
if response.status_code == 200:
return response.json()
except:
pass
return None
def graceful_shutdown():
# Stop accepting work
# Checkpoint state
# Clean up
pass
while True:
if check_interruption():
graceful_shutdown()
sys.exit(0)
time.sleep(5)
🔍 Interviewer Notes: Testing cost optimization and fault tolerance.
Q6: What are EC2 instance families and their use cases?
Technical Answer: EC2 instance families are optimized for different workloads (compute, memory, storage, GPU).
Instance Families:
| Family | Use Case | Examples |
|---|---|---|
| T (T3/T4g) | Burstable, dev/test | t3.micro, t4g.small |
| M (M6i/M6g) | General purpose | m6i.large, m6g.xlarge |
| C (C6i/C7g) | Compute optimized | c6i.2xlarge, c7g.4xlarge |
| R (R6i/X2idn) | Memory optimized | r6i.8xlarge, x2idn.24xlarge |
| I (I4i) | Storage optimized | i4i.16xlarge |
| G (G5/P4) | GPU instances | g5.xlarge, p4d.24xlarge |
| Graviton | ARM-based, cost-effective | m6g, c6g, r6g |
Selecting Instance Type:
import boto3
ec2 = boto3.client('ec2')
# Get instance types with filters
response = ec2.describe_instance_types(
Filters=[
{'Name': 'vcpu-info.default-vcpus', 'Values': ['4']},
{'Name': 'memory-info.size-in-mib', 'Values': ['16384']},
{'Name': 'processor-info.supported-architecture', 'Values': ['x86_64']}
]
)
for instance in response['InstanceTypes']:
print(f"{instance['InstanceType']}: "
f"{instance['VCpuInfo']['DefaultVCpus']} vCPUs, "
f"{instance['MemoryInfo']['SizeInMiB']} MiB")
🔍 Interviewer Notes: Testing workload optimization knowledge.
❌ Common Mistakes:
- Using M5 when C6 would be better for compute
- Not considering Graviton for cost savings
- Over-provisioning (using too large instances)
Q7: How do you configure EC2 networking?
Technical Answer: EC2 networking involves VPC, subnets, ENIs, and IP addressing.
Network Configuration:
import boto3
ec2 = boto3.client('ec2')
# Create network interface
eni = ec2.create_network_interface(
SubnetId='subnet-123',
Groups=['sg-123'], # Security groups
Description='Primary ENI',
PrivateIpAddress='10.0.1.100'
)
# Attach to instance
ec2.attach_network_interface(
NetworkInterfaceId=eni['NetworkInterface']['NetworkInterfaceId'],
InstanceId='i-123',
DeviceIndex=1 # eth1
)
# Multiple ENIs for network segmentation
# eth0: Public subnet, internet access
# eth1: Private subnet, database access only
ENI Features:
- Multiple IP addresses per ENI
- Elastic IP attachment
- Enhanced networking (ENA, EFA)
🔍 Interviewer Notes: Testing network architecture understanding.
❌ Common Mistakes:
- Not using multiple ENIs for segmentation
- Wrong subnet placement
- Not enabling enhanced networking
Q8: How do you manage EC2 storage?
Technical Answer: EC2 storage includes EBS volumes, instance store, and EFS.
Storage Options:
import boto3
ec2 = boto3.client('ec2')
# Create and attach EBS volume
volume = ec2.create_volume(
Size=100,
VolumeType='gp3', # or io2, st1, sc1
AvailabilityZone='us-east-1a',
Encrypted=True,
KmsKeyId='arn:aws:kms:us-east-1:123456789:key/...',
Iops=3000, # For io2/gp3
Throughput=125 # MB/s for gp3
)
# Attach to instance
ec2.attach_volume(
VolumeId=volume['VolumeId'],
InstanceId='i-123',
Device='/dev/sdf'
)
# Create EBS snapshot for backup
snapshot = ec2.create_snapshot(
VolumeId=volume['VolumeId'],
Description='Backup before migration'
)
Storage Types:
| Type | Use Case | Durability |
|---|---|---|
| EBS | Persistent, block storage | 99.999% |
| Instance Store | Temporary, high performance | Ephemeral |
| EFS | Shared file system | 99.999999999% |
🔍 Interviewer Notes: Testing storage architecture knowledge.
❌ Common Mistakes:
- Using instance store for persistent data
- Not encrypting EBS volumes
- Wrong volume type for workload
Q9: How do you implement EC2 user data and bootstrapping?
Technical Answer: User data scripts run at first boot to configure instances automatically.
User Data Examples:
import boto3
ec2 = boto3.client('ec2')
# Cloud-init script for Amazon Linux 2
user_data = '''#!/bin/bash
# Update system
yum update -y
# Install packages
yum install -y httpd php mysql
# Start Apache
systemctl start httpd
systemctl enable httpd
# Configure application
cat > /var/www/html/config.php << 'EOF'
<?php
$db_host = getenv('DB_HOST');
$db_user = getenv('DB_USER');
?>
EOF
# Signal CloudFormation (if used)
/opt/aws/bin/cfn-signal -e $? --stack my-stack --resource WebServer --region us-east-1
'''
# Launch with user data
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='t3.medium',
MinCount=1,
MaxCount=1,
UserData=user_data, # Base64 encoded automatically
IamInstanceProfile={'Name': 'ec2-role'},
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': 'web-server'}]
}]
)
User Data Limits:
- 16 KB text (64 KB if base64-encoded)
- Runs as root on first boot only
- Must start with shebang (#!/bin/bash) or cloud-config
🔍 Interviewer Notes: Testing automation and configuration management.
❌ Common Mistakes:
- User data too large (>16KB)
- Not handling script failures
- Not using CloudFormation signals
Q10: How do you implement EC2 key pairs and SSH access?
Technical Answer: EC2 uses SSH key pairs for secure instance access.
Key Pair Management:
import boto3
ec2 = boto3.client('ec2')
# Create key pair
key_pair = ec2.create_key_pair(
KeyName='my-key',
KeyType='rsa', # or 'ed25519'
KeyFormat='pem' # or 'ppk' for Windows
)
# Save private key (critical!)
private_key = key_pair['KeyMaterial']
with open('my-key.pem', 'w') as f:
f.write(private_key)
import os
os.chmod('my-key.pem', 0o400) # Secure permissions
# Launch with key pair
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='t3.micro',
MinCount=1,
MaxCount=1,
KeyName='my-key', # For SSH access
SecurityGroupIds=['sg-123']
)
# Delete key pair when no longer needed
ec2.delete_key_pair(KeyName='my-key')
SSH Access Best Practices:
- Never share private keys
- Use Session Manager instead of direct SSH when possible
- Rotate keys regularly
- Use Instance Connect for temporary access
🔍 Interviewer Notes: Testing security access patterns.
❌ Common Mistakes:
- Losing private key (no way to recover)
- 777 permissions on key file (security risk)
- Sharing keys between users
Q11: How do you implement EC2 load balancing?
Technical Answer: Elastic Load Balancing (ELB) distributes traffic across multiple EC2 instances.
import boto3
elbv2 = boto3.client('elbv2')
ec2 = boto3.client('ec2')
# Create Application Load Balancer
alb = elbv2.create_load_balancer(
Name='web-alb',
Subnets=['subnet-123', 'subnet-456'],
SecurityGroups=['sg-789'],
Scheme='internet-facing',
Type='application',
IpAddressType='ipv4'
)
alb_arn = alb['LoadBalancers'][0]['LoadBalancerArn']
# Create target group
tg = elbv2.create_target_group(
Name='web-tg',
Protocol='HTTP',
Port=80,
VpcId='vpc-123',
HealthCheckProtocol='HTTP',
HealthCheckPath='/health',
HealthCheckIntervalSeconds=30,
HealthCheckTimeoutSeconds=5,
HealthyThresholdCount=2,
UnhealthyThresholdCount=3
)
tg_arn = tg['TargetGroups'][0]['TargetGroupArn']
# Register targets
elbv2.register_targets(
TargetGroupArn=tg_arn,
Targets=[
{'Id': 'i-1234567890abcdef0'},
{'Id': 'i-0987654321fedcba0'}
]
)
# Create listener
elbv2.create_listener(
LoadBalancerArn=alb_arn,
Protocol='HTTP',
Port=80,
DefaultActions=[{
'Type': 'forward',
'TargetGroupArn': tg_arn
}]
)
ELB Types:
| Type | Layer | Use Case |
|---|---|---|
| ALB | 7 (HTTP/HTTPS) | Web apps, microservices |
| NLB | 4 (TCP/UDP) | Performance, static IPs |
| CLB | 4/7 | Legacy applications |
| GWLB | 3 | Network appliances |
🔍 Interviewer Notes: Testing high availability architecture.
❌ Common Mistakes:
- Wrong health check path (always 500)
- Not cross-zone load balancing
- Security group blocking health checks
Q12: How do you use Elastic IPs?
Technical Answer: Elastic IPs are static IPv4 addresses that can be remapped between instances.
import boto3
ec2 = boto3.client('ec2')
# Allocate Elastic IP
eip = ec2.allocate_address(Domain='vpc')
allocation_id = eip['AllocationId']
public_ip = eip['PublicIp']
# Associate with instance
association = ec2.associate_address(
InstanceId='i-1234567890abcdef0',
AllocationId=allocation_id
)
# Later: Reassociate to new instance (zero downtime)
# 1. Disassociate from old
ec2.disassociate_address(AssociationId=association['AssociationId'])
# 2. Associate with new
new_association = ec2.associate_address(
InstanceId='i-newinstance',
AllocationId=allocation_id
)
# Release when done
ec2.release_address(AllocationId=allocation_id)
EIP Limits:
- 5 per region (default, can be increased)
- Costs if not attached ($0.005/hour)
Best Practice: Use ALB/NLB DNS instead of EIPs when possible
🔍 Interviewer Notes: Testing static IP requirements.
❌ Common Mistakes:
- Orphaned EIPs (costs)
- Using EIPs instead of load balancers
- Not using IPv6 (free, unlimited)
Q13: How do you implement VPC peering?
Technical Answer: VPC peering connects two VPCs for private communication.
import boto3
ec2 = boto3.client('ec2')
# Create VPC peering connection
peering = ec2.create_vpc_peering_connection(
VpcId='vpc-111', # Requester
PeerVpcId='vpc-222', # Accepter
PeerRegion='us-west-2' # Cross-region peering
)
peering_id = peering['VpcPeeringConnection']['VpcPeeringConnectionId']
# Accept peering (in accepter account)
ec2.accept_vpc_peering_connection(
VpcPeeringConnectionId=peering_id
)
# Update route tables in both VPCs
ec2.create_route(
RouteTableId='rtb-requester',
DestinationCidrBlock='10.1.0.0/16', # Accepter VPC CIDR
VpcPeeringConnectionId=peering_id
)
ec2.create_route(
RouteTableId='rtb-accepter',
DestinationCidrBlock='10.0.0.0/16', # Requester VPC CIDR
VpcPeeringConnectionId=peering_id
)
# Update security groups to allow cross-VPC traffic
Peering Rules:
- No transitive peering (A-B, B-C doesn't mean A-C)
- No overlapping CIDR blocks
- Cross-region supported
- Cross-account supported
🔍 Interviewer Notes: Testing multi-VPC architecture.
❌ Common Mistakes:
- Missing route table entries
- Overlapping CIDRs
- Expecting transitive routing
Q14: How do you implement NAT Gateway?
Technical Answer: NAT Gateway allows private subnet instances to access internet without inbound access.
import boto3
ec2 = boto3.client('ec2')
# Allocate Elastic IP for NAT Gateway
eip = ec2.allocate_address(Domain='vpc')
# Create NAT Gateway in public subnet
nat_gw = ec2.create_nat_gateway(
SubnetId='subnet-public-1a', # Public subnet
AllocationId=eip['AllocationId'],
TagSpecifications=[{
'ResourceType': 'natgateway',
'Tags': [{'Key': 'Name', 'Value': 'Production-NAT'}]
}]
)
nat_gw_id = nat_gw['NatGateway']['NatGatewayId']
# Wait for available
waiter = ec2.get_waiter('nat_gateway_available')
waiter.wait(NatGatewayIds=[nat_gw_id])
# Update private subnet route table
ec2.create_route(
RouteTableId='rtb-private',
DestinationCidrBlock='0.0.0.0/0',
NatGatewayId=nat_gw_id
)
Architecture:
Internet
↓
IGW (public subnet)
↓
NAT Gateway (public subnet, has EIP)
↓
Private Subnet Instances
(No public IPs, can reach out only)
NAT Options:
| Option | Availability | Bandwidth | Management |
|---|---|---|---|
| NAT Gateway | 99.99% SLA | Up to 45 Gbps | Managed |
| NAT Instance | Self-managed | Depends on size | Manual |
🔍 Interviewer Notes: Testing private subnet connectivity.
❌ Common Mistakes:
- NAT Gateway in private subnet (must be public)
- Wrong route table association
- Not using multiple AZs for HA
Q15: How do you implement EC2 Systems Manager?
Technical Answer: Systems Manager (SSM) provides unified management for EC2 instances.
import boto3
ssm = boto3.client('ssm')
ec2 = boto3.client('ec2')
# Run command on multiple instances
response = ssm.send_command(
InstanceIds=['i-123', 'i-456'],
DocumentName='AWS-RunShellScript',
Parameters={
'commands': [
'yum update -y',
'systemctl restart nginx',
'echo "Update completed at $(date)"'
]
},
TimeoutSeconds=300
)
# Get command output
command_id = response['Command']['CommandId']
output = ssm.get_command_invocation(
CommandId=command_id,
InstanceId='i-123'
)
print(f"Status: {output['Status']}")
print(f"Output: {output['StandardOutputContent']}")
# Patch management
ssm.send_command(
InstanceIds=['i-123'],
DocumentName='AWS-RunPatchBaseline',
Parameters={
'Operation': ['Install'],
'RebootOption': ['RebootIfNeeded']
}
)
# Session Manager (SSH alternative without key management)
# aws ssm start-session --target i-123
SSM Features:
- Run Command (remote execution)
- Session Manager (SSH alternative)
- Patch Manager (automated patching)
- Parameter Store (secure config)
- Automation (runbooks)
- Inventory (asset tracking)
🔍 Interviewer Notes: Testing operational management.
❌ Common Mistakes:
- IAM role without SSM permissions
- No SSM agent installed
- Using SSH keys when SSM available
Q16: How do you configure EC2 monitoring?
Technical Answer: EC2 monitoring uses CloudWatch for metrics and CloudWatch Agent for detailed monitoring.
import boto3
cloudwatch = boto3.client('cloudwatch')
ec2 = boto3.client('ec2')
# Enable detailed monitoring (1-min vs 5-min intervals)
ec2.monitor_instances(InstanceIds=['i-123'])
# Create CloudWatch alarm for CPU
cloudwatch.put_metric_alarm(
AlarmName='HighCPU',
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistic='Average',
Period=300,
EvaluationPeriods=2,
Threshold=80,
ComparisonOperator='GreaterThanThreshold',
Dimensions=[{
'Name': 'InstanceId',
'Value': 'i-123'
}],
AlarmActions=['arn:aws:sns:us-east-1:123456789:alerts']
)
# CloudWatch Agent config for memory/disk
# /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
{
"metrics": {
"namespace": "MyApp",
"metrics_collected": {
"mem": {
"measurement": ["mem_used_percent"],
"metrics_collection_interval": 60
},
"disk": {
"measurement": ["disk_used_percent"],
"resources": ["/"],
"metrics_collection_interval": 60
}
}
}
}
Key Metrics:
CPUUtilization- CPU usageNetworkIn/Out- Network trafficDiskReadOps/WriteOps- I/O operationsStatusCheckFailed- Instance/system health
🔍 Interviewer Notes: Testing observability setup.
❌ Common Mistakes:
- Basic monitoring only (5-min granularity)
- No memory/disk metrics (need agent)
- Not setting up alarms
Q17: What is EC2 Auto Scaling?
Technical Answer: Auto Scaling automatically adjusts EC2 capacity based on demand or schedule.
import boto3
autoscaling = boto3.client('autoscaling')
# Create launch template
ec2 = boto3.client('ec2')
template = ec2.create_launch_template(
LaunchTemplateName='web-server',
LaunchTemplateData={
'ImageId': 'ami-0c55b159cbfafe1f0',
'InstanceType': 't3.medium',
'KeyName': 'my-key',
'SecurityGroupIds': ['sg-123'],
'UserData': user_data_base64,
'IamInstanceProfile': {'Name': 'ec2-role'}
}
)
# Create Auto Scaling group
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='web-asg',
LaunchTemplate={
'LaunchTemplateId': template['LaunchTemplate']['LaunchTemplateId'],
'Version': '$Latest'
},
MinSize=2,
MaxSize=10,
DesiredCapacity=2,
VPCZoneIdentifier='subnet-123,subnet-456',
TargetGroupARNs=['arn:aws:elasticloadbalancing:...:targetgroup/web-tg'],
HealthCheckType='ELB', # or 'EC2'
HealthCheckGracePeriod=300,
Tags=[{
'Key': 'Name',
'Value': 'web-server',
'PropagateAtLaunch': True
}]
)
# Attach scaling policy (target tracking)
autoscaling.put_scaling_policy(
AutoScalingGroupName='web-asg',
PolicyName='target-tracking-policy',
PolicyType='TargetTrackingScaling',
TargetTrackingConfiguration={
'PredefinedMetricSpecification': {
'PredefinedMetricType': 'ASGAverageCPUUtilization'
},
'TargetValue': 60.0,
'ScaleOutCooldown': 300,
'ScaleInCooldown': 600
}
)
Scaling Types:
| Type | Trigger | Use Case |
|---|---|---|
| Dynamic | CloudWatch alarms | Variable load |
| Target Tracking | Keep metric at target | Steady load |
| Predictive | Machine learning | Predictable patterns |
| Scheduled | Time-based | Known schedule |
🔍 Interviewer Notes: Testing elasticity understanding.
❌ Common Mistakes:
- No health checks (unhealthy instances kept)
- Cooldown too short (flapping)
- Not using launch templates
Q18: How do you implement EC2 security groups?
Technical Answer: Security groups act as virtual firewalls controlling inbound/outbound traffic.
import boto3
ec2 = boto3.client('ec2')
# Create security group
sg = ec2.create_security_group(
GroupName='web-server-sg',
Description='Security group for web servers',
VpcId='vpc-123'
)
sg_id = sg['GroupId']
# Add inbound rules
ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 80,
'ToPort': 80,
'IpRanges': [{'CidrIp': '0.0.0.0/0', 'Description': 'HTTP'}]
},
{
'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [{'CidrIp': '0.0.0.0/0', 'Description': 'HTTPS'}]
},
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'UserIdGroupPairs': [{'GroupId': 'sg-bastion', 'Description': 'SSH from bastion only'}]
}
]
)
# Security group rules are stateful
# If inbound HTTP is allowed, return traffic is automatically allowed
# No need for explicit outbound rule for responses
Security Group Features:
- Stateful (return traffic auto-allowed)
- Only allow rules (no deny)
- Applied at instance level
- Changes immediate effect
- Can reference other security groups
🔍 Interviewer Notes: Testing network security fundamentals.
❌ Common Mistakes:
- 0.0.0.0/0 for SSH (security risk)
- Not using security group references
- Too many rules (limit: 60 inbound, 60 outbound)
Q19: What is EC2 instance metadata?
Technical Answer: Instance Metadata Service (IMDS) provides data about instances via a local endpoint.
import requests
# IMDSv2 (recommended - session-based)
# Step 1: Get session token
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=5
).text
# Step 2: Use token for metadata requests
metadata = requests.get(
'http://169.254.169.254/latest/meta-data/',
headers={'X-aws-ec2-metadata-token': token},
timeout=5
).text
# Common metadata endpoints
endpoints = {
'ami-id': '/latest/meta-data/ami-id',
'instance-id': '/latest/meta-data/instance-id',
'instance-type': '/latest/meta-data/instance-type',
'local-ipv4': '/latest/meta-data/local-ipv4',
'public-ipv4': '/latest/meta-data/public-ipv4',
'availability-zone': '/latest/meta-data/placement/availability-zone',
'iam-role': '/latest/meta-data/iam/security-credentials/',
'user-data': '/latest/user-data'
}
# Get IAM credentials (temporary)
creds = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/ec2-role',
headers={'X-aws-ec2-metadata-token': token}
).json()
IMDSv2 Benefits:
- Session-based (prevents SSRF attacks)
- TTL for tokens
- Required by default on new instances
🔍 Interviewer Notes: Testing security awareness.
❌ Common Mistakes:
- Using IMDSv1 (vulnerable to SSRF)
- Hardcoding metadata endpoint
- Not handling request failures
Q20: How do you implement EC2 placement groups?
Technical Answer: Placement groups determine how instances are placed on underlying hardware.
import boto3
ec2 = boto3.client('ec2')
# Create cluster placement group (HPC - low latency)
cluster_pg = ec2.create_placement_group(
GroupName='hpc-cluster',
Strategy='cluster',
Tags=[{'Key': 'Name', 'Value': 'HPC Cluster'}]
)
# Create spread placement group (high availability)
spread_pg = ec2.create_placement_group(
GroupName='critical-apps',
Strategy='spread'
)
# Create partition placement group (large distributed workloads)
partition_pg = ec2.create_placement_group(
GroupName='partitioned-app',
Strategy='partition',
PartitionCount=3
)
# Launch instances in placement group
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='c6i.24xlarge',
MinCount=4,
MaxCount=4,
Placement={'GroupName': 'hpc-cluster'},
EnaSupport=True # Enhanced networking for cluster
)
Placement Strategies:
| Strategy | Use Case | Limitations |
|---|---|---|
| Cluster | HPC, low latency | Same AZ, 7 instances per AZ |
| Spread | Critical apps, fault tolerance | 7 instances per AZ |
| Partition | Large distributed systems | 7 partitions per AZ |
🔍 Interviewer Notes: Testing placement optimization.
❌ Common Mistakes:
- Wrong strategy for workload
- Not using enhanced networking with cluster
- Exceeding placement limits
Q21: How do you use EC2 dedicated hosts?
Technical Answer: Dedicated hosts are physical servers dedicated for your use.
import boto3
ec2 = boto3.client('ec2')
# Allocate dedicated host
host = ec2.allocate_hosts(
InstanceType='m5.large',
AvailabilityZone='us-east-1a',
AutoPlacement='on',
Quantity=1,
HostRecovery='on'
)
host_id = host['HostIds'][0]
# Launch instance on dedicated host
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
Placement={
'HostId': host_id,
'Tenancy': 'host'
}
)
# Release when done
ec2.release_hosts(HostIds=[host_id])
Use Cases:
- Software licenses (per-socket, per-core)
- Regulatory compliance (physical isolation)
- Bring Your Own License (BYOL)
vs Dedicated Instances:
| Feature | Dedicated Hosts | Dedicated Instances |
|---|---|---|
| Visibility | See sockets/cores | No visibility |
| BYOL | Yes | Limited |
| Control | Instance placement | AWS managed |
🔍 Interviewer Notes: Testing licensing and compliance.
❌ Common Mistakes:
- Using dedicated instances when hosts needed for BYOL
- Not monitoring host utilization
- Wrong instance type on host
Q22: How do you implement EC2 Capacity Reservations?
Technical Answer: Capacity Reservations reserve capacity in a specific AZ without upfront commitment.
import boto3
ec2 = boto3.client('ec2')
# Create capacity reservation
cr = ec2.create_capacity_reservation(
InstanceType='m5.xlarge',
InstancePlatform='Linux/UNIX',
AvailabilityZone='us-east-1a',
InstanceCount=5,
EndDateType='unlimited', # or 'limited' with EndDate
InstanceMatchCriteria='open', # Any instance can use
TagSpecifications=[{
'ResourceType': 'capacity-reservation',
'Tags': [{'Key': 'Name', 'Value': 'Production-Capacity'}]
}]
)
cr_id = cr['CapacityReservation']['CapacityReservationId']
# Launch into capacity reservation
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='m5.xlarge',
MinCount=1,
MaxCount=1,
Placement={
'AvailabilityZone': 'us-east-1a',
'CapacityReservationSpecification': {
'CapacityReservationTarget': {
'CapacityReservationId': cr_id
}
}
}
)
# Modify to target specific reservation
ec2.modify_capacity_reservation(
CapacityReservationId=cr_id,
InstanceCount=10 # Increase reserved capacity
)
Capacity Reservations vs Savings Plans:
| Feature | Capacity Reservation | Savings Plans |
|---|---|---|
| Capacity guarantee | Yes | No |
| Discount | No | Yes |
| Flexibility | AZ-specific | Region-wide |
| Commitment | None | 1-3 years |
🔍 Interviewer Notes: Testing capacity planning.
❌ Common Mistakes:
- Not combining with Savings Plans
- Wrong AZ specification
- Not monitoring utilization
Q23: How do you implement EC2 Fleet?
Technical Answer: EC2 Fleet simplifies provisioning across instance types, AZs, and purchase options.
import boto3
ec2 = boto3.client('ec2')
# Create EC2 Fleet for diverse capacity
fleet = ec2.create_fleet(
LaunchTemplateConfigs=[{
'LaunchTemplateSpecification': {
'LaunchTemplateName': 'web-server',
'Version': '1'
},
'Overrides': [
{'InstanceType': 'm5.large', 'SubnetId': 'subnet-1a', 'WeightedCapacity': 1},
{'InstanceType': 'm5.xlarge', 'SubnetId': 'subnet-1a', 'WeightedCapacity': 2},
{'InstanceType': 'm5.large', 'SubnetId': 'subnet-1b', 'WeightedCapacity': 1},
{'InstanceType': 'm5.xlarge', 'SubnetId': 'subnet-1b', 'WeightedCapacity': 2}
]
}],
TargetCapacitySpecification={
'TotalTargetCapacity': 10,
'OnDemandTargetCapacity': 4,
'SpotTargetCapacity': 6,
'DefaultTargetCapacityType': 'spot'
},
SpotOptions={
'AllocationStrategy': 'capacity-optimized',
'MaxTotalPrice': '1.50' # Max $1.50/hour for all Spot
},
OnDemandOptions={
'AllocationStrategy': 'lowest-price'
},
Type='maintain' # 'maintain' or 'request'
)
fleet_id = fleet['FleetId']
# Describe fleet
fleet_info = ec2.describe_fleets(FleetIds=[fleet_id])
print(f"Target capacity: {fleet_info['Fleets'][0]['TargetCapacitySpecification']['TotalTargetCapacity']}")
print(f"Fulfilled capacity: {fleet_info['Fleets'][0]['FulfilledCapacity']}")
Fleet Benefits:
- Single API for multiple instance types
- Automatic Spot diversification
- Capacity-optimized Spot allocation
- Real-time capacity monitoring
🔍 Interviewer Notes: Testing advanced provisioning.
❌ Common Mistakes:
- Not using diverse instance types
- Wrong allocation strategy
- No price protection
Q24: How do you implement EC2 instance stores?
Technical Answer: Instance store provides temporary block-level storage physically attached to the host.
import boto3
ec2 = boto3.client('ec2')
# Launch with instance store volumes
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='c6id.4xlarge', # 'd' = instance store
MinCount=1,
MaxCount=1,
BlockDeviceMappings=[
{
'DeviceName': '/dev/sdb',
'VirtualName': 'ephemeral0' # First instance store
},
{
'DeviceName': '/dev/sdc',
'VirtualName': 'ephemeral1' # Second instance store
}
],
UserData='''#!/bin/bash
# RAID 0 multiple instance stores for better performance
yum install -y mdadm
mdadm --create /dev/md0 --level=0 --raid-devices=2 /dev/nvme1n1 /dev/nvme2n1
mkfs.xfs /dev/md0
mkdir -p /data
mount /dev/md0 /data
# Data is lost when instance stops/terminates!
echo "instance-store mounted on /data"
'''
)
Instance Store Characteristics:
| Feature | Description |
|---|---|
| Performance | Very high IOPS, low latency |
| Durability | Ephemeral (lost on stop/terminate) |
| Use Case | Cache, buffers, temporary files |
| Cost | Included with instance |
Instance Store vs EBS:
| Instance Store | EBS | |
|---|---|---|
| Persistence | No | Yes |
| Snapshot | No | Yes |
| Performance | Better | Good |
| Resize | No | Yes |
🔍 Interviewer Notes: Testing storage selection.
❌ Common Mistakes:
- Storing persistent data on instance store
- Not backing up before stop
- Wrong instance type (no 'd' suffix)
Q25: How do you use EC2 serial console?
Technical Answer: EC2 Serial Console provides serial port access for troubleshooting without network.
# Enable serial console (must be enabled first)
aws ec2 modify-serial-console-access --enabled
# Connect to serial console
aws ec2-instance-connect send-serial-console-ssh-public-key \
--instance-id i-1234567890abcdef0 \
--serial-port 0 \
--ssh-public-key file://my_key.pub
# Then SSH to serial console
ssh -i my_key root@i-1234567890abcdef0.serial-console.ec2-instance-connect.us-east-1.aws
Use Cases:
- Recovery when SSH/RDP not working
- Network configuration debugging
- Boot issues troubleshooting
- Password recovery
- Firewall misconfiguration fix
Requirements:
- IAM permissions:
ec2-instance-connect:SendSerialConsoleSSHPublicKey - Instance must be running
- OS must have serial console enabled
🔍 Interviewer Notes: Testing troubleshooting capabilities.
❌ Common Mistakes:
- Not enabling serial console before issue
- Trying to use on stopped instances
- Not configuring OS serial console
Q26: How do you create and manage EBS snapshots?
Technical Answer: EBS snapshots are point-in-time backups of EBS volumes stored in S3. They incrementally back up only changed blocks after the first full snapshot.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create snapshot from volume
snapshot = ec2.create_snapshot(
VolumeId='vol-1234567890abcdef0',
Description='Daily backup of web server data volume',
TagSpecifications=[{
'ResourceType': 'snapshot',
'Tags': [{'Key': 'Name', 'Value': 'web-data-backup-20240501'}]
}]
)
snapshot_id = snapshot['SnapshotId']
# Wait for snapshot completion
waiter = ec2.get_waiter('snapshot_completed')
waiter.wait(SnapshotIds=[snapshot_id])
# Create volume from snapshot
restored_volume = ec2.create_volume(
SnapshotId=snapshot_id,
AvailabilityZone='us-east-1a',
VolumeType='gp3',
Encrypted=True
)
🔍 Interviewer Notes: Testing backup and disaster recovery knowledge for EBS.
❌ Common Mistakes:
- Taking snapshots of mounted volumes without freezing filesystem
- Not encrypting snapshots
- Deleting snapshots before confirming volume restoration
Q27: How do you encrypt EBS volumes and snapshots?
Technical Answer: EBS encryption uses AWS KMS keys to encrypt data at rest, in transit, and all snapshots. Encryption is enabled at volume creation or by modifying existing volumes.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create encrypted EBS volume
volume = ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='gp3',
Encrypted=True,
KmsKeyId='arn:aws:kms:us-east-1:123456789:key/1234abcd-12ab-34cd-56ef-1234567890ab'
)
# Enable encryption by default for all new volumes
ec2.enable_ebs_encryption_by_default()
# Encrypt existing unencrypted volume via snapshot
snapshot = ec2.create_snapshot(VolumeId='vol-unencrypted', Description='Snapshot for encryption')
ec2.wait_until_snapshot_completed(SnapshotIds=[snapshot['SnapshotId']])
encrypted_volume = ec2.create_volume(
SnapshotId=snapshot['SnapshotId'],
AvailabilityZone='us-east-1a',
Encrypted=True
)
🔍 Interviewer Notes: Testing data security and compliance practices.
❌ Common Mistakes:
- Not enabling encryption by default
- Using default AWS managed key instead of customer managed key
- Forgetting that snapshots of encrypted volumes are automatically encrypted
Q28: What are EBS snapshots and how do you use them for cross-region backup?
Technical Answer: EBS snapshots are incremental backups stored in S3, and can be copied to other AWS regions for disaster recovery. Cross-region copies enable regional failover for critical workloads.
Code/Config Example:
import boto3
ec2_us_east = boto3.client('ec2', region_name='us-east-1')
ec2_us_west = boto3.client('ec2', region_name='us-west-2')
# Create initial snapshot in us-east-1
snapshot = ec2_us_east.create_snapshot(
VolumeId='vol-1234567890abcdef0',
Description='Cross-region backup snapshot'
)
snapshot_id = snapshot['SnapshotId']
# Wait for snapshot completion
waiter = ec2_us_east.get_waiter('snapshot_completed')
waiter.wait(SnapshotIds=[snapshot_id])
# Copy snapshot to us-west-2
copied_snapshot = ec2_us_east.copy_snapshot(
SourceSnapshotId=snapshot_id,
SourceRegion='us-east-1',
DestinationRegion='us-west-2',
Description='Disaster recovery copy',
Encrypted=True
)
🔍 Interviewer Notes: Testing cross-region DR strategies.
❌ Common Mistakes:
- Not encrypting cross-region copied snapshots
- Copying snapshots without waiting for completion
- Not cleaning up old snapshots in source region
Q29: How do you share EBS snapshots across AWS accounts?
Technical Answer: EBS snapshots can be shared with other AWS accounts by modifying snapshot permissions. Shared snapshots can be used to create volumes in the target account but cannot be modified by the target account.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Share snapshot with target account
ec2.modify_snapshot_attribute(
SnapshotId='snap-1234567890abcdef0',
Attribute='createVolumePermission',
OperationType='add',
UserIds=['123456789012'] # Target AWS account ID
)
# Share snapshot publicly (use with caution!)
# ec2.modify_snapshot_attribute(
# SnapshotId='snap-1234567890abcdef0',
# Attribute='createVolumePermission',
# OperationType='add',
# GroupNames=['all']
# )
# Create volume from shared snapshot in target account
target_ec2 = boto3.client('ec2')
volume = target_ec2.create_volume(
SnapshotId='snap-1234567890abcdef0',
AvailabilityZone='us-east-1a',
VolumeType='gp3'
)
🔍 Interviewer Notes: Testing multi-account resource sharing.
❌ Common Mistakes:
- Sharing snapshots publicly by mistake
- Not removing permissions when no longer needed
- Trying to modify shared snapshots in target account
Q30: What are EBS volume attachment limits and how do you work with them?
Technical Answer: Each EC2 instance has a maximum number of EBS volumes it can attach, varying by instance type. Most instances support 28 attachments (including root volume) but some smaller instances support fewer.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Check instance EBS attachment limits
response = ec2.describe_instance_types(
InstanceTypes=['m5.large', 'c6i.xlarge']
)
for instance in response['InstanceTypes']:
ebs_info = instance.get('EbsInfo', {})
print(f"{instance['InstanceType']}: Max EBS optimized: {ebs_info.get('EbsOptimizedSupport', 'N/A')}")
# Attach multiple volumes
for i in range(5):
volume = ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=10,
VolumeType='gp3'
)
ec2.attach_volume(
VolumeId=volume['VolumeId'],
InstanceId='i-1234567890abcdef0',
Device=f'/dev/sd{i+1}'
)
🔍 Interviewer Notes: Testing instance storage limits knowledge.
❌ Common Mistakes:
- Exceeding instance EBS attachment limits
- Using same device name for multiple volumes
- Not considering EBS optimization for multiple volumes
Q31: What are EC2 purchasing options and when to use each?
Technical Answer: EC2 offers On-Demand, Reserved Instances, Spot Instances, and Savings Plans to match different workload requirements and cost profiles. On-Demand provides pay-as-you-go flexibility, Reserved offers discounts for 1-3 year commitments, Spot uses spare capacity at up to 90% discount, and Savings Plans offer flexible region-wide discounts.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch On-Demand instance
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
InstanceMarketOptions={'MarketType': 'on-demand'} # Default
)
# Launch Spot instance
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
InstanceMarketOptions={
'MarketType': 'spot',
'SpotOptions': {
'MaxPrice': '0.05',
'SpotInstanceType': 'one-time' # or 'persistent'
}
}
)
🔍 Interviewer Notes: Testing cost optimization and workload matching.
❌ Common Mistakes:
- Using On-Demand for predictable steady-state workloads
- Not setting MaxPrice for Spot instances
- Confusing Reserved Instances with Savings Plans
Q32: How do you purchase EC2 Reserved Instances?
Technical Answer: Reserved Instances (RIs) provide 30-75% discounts over On-Demand pricing in exchange for 1-3 year commitments. RIs can be Standard (rigid) or Convertible (flexible instance family), and regional or zonal.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Describe available Reserved Instance offerings
offerings = ec2.describe_reserved_instances_offerings(
InstanceType='m5.large',
OfferingClass='Convertible', # or 'Standard'
ProductDescription='Linux/UNIX',
Duration=94608000 # 3 years in seconds (31536000 = 1 year)
)
# Purchase Reserved Instance
ri = ec2.purchase_reserved_instances_offering(
ReservedInstancesOfferingId=offerings['ReservedInstancesOfferings'][0]['ReservedInstancesOfferingId'],
InstanceCount=5
)
🔍 Interviewer Notes: Testing long-term cost commitment strategies.
❌ Common Mistakes:
- Buying zonal RIs when regional flexibility is needed
- Not using Convertible RIs for changing instance needs
- Buying RIs without checking utilization first
Q33: What are EC2 Savings Plans and how do they differ from Reserved Instances?
Technical Answer: Savings Plans provide flexible cost savings (up to 72%) in exchange for 1-3 year hourly spend commitments. Unlike RIs, Savings Plans apply to any instance family, region, OS, or tenancy that matches the plan type (Compute Savings Plans or EC2 Instance Savings Plans).
Code/Config Example:
import boto3
ce = boto3.client('ce') # Cost Explorer
# Describe Savings Plans offerings
savings_plans = ce.describe_savings_plans_offerings(
PaymentOption='PARTIAL_UPFRONT',
ProductCode='AmazonEC2',
PlanType='COMPUTE_SP'
)
# Purchase Compute Savings Plan (flexible across instance families)
# Note: Savings Plans are purchased via AWS Console or CLI, not directly via boto3
# aws savingsplans create-savings-plan --offering-id "sp-123" --commitment "10.0" --upfront-payment "500.0"
🔍 Interviewer Notes: Testing modern cost optimization approaches.
❌ Common Mistakes:
- Using RIs when workload flexibility is needed
- Not matching Savings Plan type to workload
- Over-committing hourly spend
Q34: How do you handle EC2 Spot Instance interruptions?
Technical Answer: Spot Instances can be interrupted with a 2-minute notification when AWS needs the capacity back. Handle interruptions by checkpointing state, using Spot interruption queues, or using capacity-optimized allocation to reduce interruption probability.
Code/Config Example:
import boto3
import requests
# Check for Spot interruption notice
def check_spot_interruption():
try:
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '300'}
).text
response = requests.get(
'http://169.254.169.254/latest/meta-data/spot/instance-action',
headers={'X-aws-ec2-metadata-token': token}
)
if response.status_code == 200:
return response.json() # e.g., {"action": "stop", "time": "2024-05-01T12:00:00Z"}
except:
pass
return None
# Set up CloudWatch alarm for Spot interruption
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_alarm(
AlarmName='spot-interruption',
MetricName='StatusCheckFailed_System',
Namespace='AWS/EC2',
Dimensions=[{'Name': 'InstanceId', 'Value': 'i-123'}],
Period=60,
EvaluationPeriods=1,
Threshold=1,
ComparisonOperator='GreaterThanOrEqualToThreshold',
AlarmActions=['arn:aws:sns:us-east-1:123456789:spot-alerts']
)
🔍 Interviewer Notes: Testing fault tolerance for Spot workloads.
❌ Common Mistakes:
- Not handling 2-minute interruption notice
- Using Spot for stateful workloads without checkpointing
- Not using capacity-optimized allocation
Q35: What is EC2 Capacity-Optimized Spot allocation?
Technical Answer: Capacity-Optimized Spot allocation selects instance types with the lowest interruption probability by analyzing historical Spot interruption data. This reduces Spot interruptions by up to 80% compared to lowest-price allocation.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create Spot Fleet with capacity-optimized strategy
spot_fleet = ec2.request_spot_fleet(
SpotFleetRequestConfig={
'IamFleetRole': 'arn:aws:iam::123456789:role/spot-fleet-role',
'AllocationStrategy': 'capacityOptimized',
'TargetCapacity': 10,
'LaunchTemplateConfigs': [{
'LaunchTemplateSpecification': {
'LaunchTemplateId': 'lt-1234567890abcdef0',
'Version': '1'
},
'Overrides': [
{'InstanceType': 'm5.large'},
{'InstanceType': 'm5a.large'},
{'InstanceType': 'm6i.large'}
]
}]
}
)
# Auto Scaling group with Spot and capacity-optimized
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='spot-asg',
MixedInstancesPolicy={
'LaunchTemplate': {
'LaunchTemplateId': 'lt-1234567890abcdef0',
'Version': '1'
},
'InstancesDistribution': {
'OnDemandPercentageAboveBaseCapacity': 20,
'SpotAllocationStrategy': 'capacity-optimized'
}
},
MinSize=2,
MaxSize=10
)
🔍 Interviewer Notes: Testing advanced Spot configuration.
❌ Common Mistakes:
- Using lowest-price instead of capacity-optimized
- Not diversifying instance types in Spot requests
- Not mixing On-Demand with Spot for critical workloads
Q36: How do you select the right EC2 instance type for a workload?
Technical Answer: Select instance types based on workload requirements: compute-optimized (C6i) for HPC, memory-optimized (R6i) for databases, storage-optimized (I4i) for NoSQL, and general-purpose (M6i) for web servers. Use Compute Optimizer to right-size existing instances.
Code/Config Example:
import boto3
compute_optimizer = boto3.client('compute-optimizer')
# Get EC2 instance recommendations
recommendations = compute_optimizer.get_ec2_instance_recommendations(
InstanceArns=['arn:aws:ec2:us-east-1:123456789:instance/i-1234567890abcdef0']
)
for rec in recommendations['instanceRecommendations']:
print(f"Current: {rec['currentInstanceType']}")
for recommendation in rec['recommendationOptions']:
print(f"Recommended: {recommendation['instanceType']}, Savings: {recommendation['savings']}%")
🔍 Interviewer Notes: Testing workload matching and cost optimization.
❌ Common Mistakes:
- Over-provisioning instance size
- Not using Graviton for cost efficiency
- Ignoring Compute Optimizer recommendations
Q37: What are EC2 burstable instances (T3/T4g) and how do they work?
Technical Answer: T3/T4g burstable instances provide a baseline CPU performance with the ability to burst above baseline using CPU credits. Credits accumulate when CPU usage is below baseline and are consumed when bursting. T4g uses Graviton processors for better price/performance.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch T3 burstable instance
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='t3.medium', # Baseline 40% CPU usage
MinCount=1,
MaxCount=1,
CreditSpecification={'CpuCredits': 'standard'} # or 'unlimited'
)
# Check CPU credit balance
cloudwatch = boto3.client('cloudwatch')
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='CPUCreditBalance',
Dimensions=[{'Name': 'InstanceId', 'Value': 'i-123'}],
StartTime='2024-05-01T00:00:00Z',
EndTime='2024-05-01T23:59:59Z',
Period=3600,
Statistics=['Average']
)
🔍 Interviewer Notes: Testing burstable instance use cases.
❌ Common Mistakes:
- Using T3 for sustained high CPU workloads
- Not monitoring CPU credit balance
- Using standard credits instead of unlimited for critical bursts
Q38: What are EC2 Graviton instances and their benefits?
Technical Answer: Graviton instances are powered by AWS-designed ARM-based processors, offering up to 40% better price/performance over x86 instances for compatible workloads. Graviton 3 (M7g, C7g, R7g) provides better performance for compute-intensive workloads.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch Graviton instance
ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0', # Amazon Linux 2 ARM AMI
InstanceType='m7g.medium', # Graviton 3 general purpose
MinCount=1,
MaxCount=1,
UserData='''#!/bin/bash
uname -m # Should output aarch64 for Graviton
yum install -y python3
'''
)
# Check instance architecture
response = ec2.describe_instances(InstanceIds=['i-123'])
arch = response['Reservations'][0]['Instances'][0]['Architecture'] # arm64
🔍 Interviewer Notes: Testing cost optimization with ARM instances.
❌ Common Mistakes:
- Using x86 AMIs with Graviton instances
- Not testing application compatibility with ARM
- Ignoring Graviton for compatible workloads
Q39: What are EC2 Dedicated Instances and how do they differ from Dedicated Hosts?
Technical Answer: Dedicated Instances run on hardware dedicated to a single AWS account but AWS manages instance placement. Dedicated Hosts are physical servers fully dedicated to your account with visibility into sockets/cores for BYOL (Bring Your Own License) compliance.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch Dedicated Instance
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
Placement={'Tenancy': 'dedicated'} # Dedicated Instance
)
# Launch on Dedicated Host
host = ec2.allocate_hosts(
InstanceType='m5.large',
AvailabilityZone='us-east-1a',
Quantity=1
)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
Placement={'Tenancy': 'host', 'HostId': host['HostIds'][0]}
)
🔍 Interviewer Notes: Testing tenancy and licensing compliance.
❌ Common Mistakes:
- Using Dedicated Instances for BYOL (need hosts)
- Not tracking Dedicated Host utilization
- Paying for unused Dedicated Host capacity
Q40: What are EC2 Capacity Blocks for ML workloads?
Technical Answer: Capacity Blocks reserve batch compute capacity for machine learning training workloads on accelerated instances (P4, P5) for a specific time window. They guarantee access to scarce GPU capacity for time-bound ML projects.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Purchase Capacity Block for ML training
capacity_block = ec2.purchase_capacity_block(
CapacityBlockOfferingId='offering-1234567890abcdef0',
PaymentOption='ALL_UPFRONT'
)
# Launch instance into Capacity Block
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='p4d.24xlarge',
MinCount=1,
MaxCount=1,
Placement={
'Tenancy': 'capacity-block',
'CapacityBlockId': capacity_block['CapacityBlockId']
}
)
🔍 Interviewer Notes: Testing specialized ML workload provisioning.
❌ Common Mistakes:
- Not reserving Capacity Blocks early for scarce GPU types
- Letting Capacity Block time window expire unused
- Using On-Demand for time-bound ML training
Q41: How do you configure Elastic Network Interfaces (ENIs) for EC2?
Technical Answer: ENIs are virtual network cards that can be attached to EC2 instances for network segmentation, multiple IP addresses, or moving network interfaces between instances.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create ENI
eni = ec2.create_network_interface(
SubnetId='subnet-123456',
Description='Secondary ENI for database traffic',
Groups=['sg-db-security-group'],
PrivateIpAddresses=[
{'PrivateIpAddress': '10.0.1.100', 'Primary': True},
{'PrivateIpAddress': '10.0.1.101', 'Primary': False}
]
)
# Attach ENI to instance
ec2.attach_network_interface(
NetworkInterfaceId=eni['NetworkInterface']['NetworkInterfaceId'],
InstanceId='i-1234567890abcdef0',
DeviceIndex=1 # eth1
)
# Detach ENI
ec2.detach_network_interface(
NetworkInterfaceId=eni['NetworkInterface']['NetworkInterfaceId'],
InstanceId='i-1234567890abcdef0'
)
🔍 Interviewer Notes: Testing network segmentation and multi-homed instance configuration.
❌ Common Mistakes:
- Attaching ENIs to instances in different AZs
- Exceeding ENI attachment limits per instance
- Forgetting to configure OS-level networking for secondary ENIs
Q42: What are Elastic IPs and when should you use them?
Technical Answer: Elastic IPs are static IPv4 addresses that can be remapped between EC2 instances, providing a fixed public IP for services that require consistent endpoints. Prefer using Load Balancers over Elastic IPs for most production workloads.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Allocate Elastic IP
eip = ec2.allocate_address(Domain='vpc')
eip_allocation_id = eip['AllocationId']
eip_public_ip = eip['PublicIp']
# Associate with instance
ec2.associate_address(
AllocationId=eip_allocation_id,
InstanceId='i-1234567890abcdef0'
)
# Reassociate to new instance (zero downtime for some use cases)
ec2.reassociate_address(
AllocationId=eip_allocation_id,
InstanceId='i-newinstance'
)
# Release when no longer needed
ec2.release_address(AllocationId=eip_allocation_id)
🔍 Interviewer Notes: Testing static IP requirements and cost awareness (EIPs cost when not attached).
❌ Common Mistakes:
- Leaving orphaned EIPs (incurs hourly charges)
- Using EIPs instead of DNS CNAME or Load Balancers
- Not tracking EIP usage across regions
Q43: How do you enable Enhanced Networking for EC2 instances?
Technical Answer: Enhanced Networking uses single root I/O virtualization (SR-IOV) to provide high throughput, low latency, and low jitter for supported EC2 instance types. Most modern instances (C5, M5, R5, etc.) support Enhanced Networking via ENA (Elastic Network Adapter).
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance with Enhanced Networking enabled (default for supported types)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.large', # Supports ENA Enhanced Networking
MinCount=1,
MaxCount=1,
EnaSupport=True, # Explicitly enable if needed
TagSpecifications=[{'ResourceType': 'instance', 'Tags': [{'Key': 'EnhancedNetworking', 'Value': 'enabled'}]}]
)
# Verify ENA support on running instance
response = ec2.describe_instances(InstanceIds=['i-123'])
ena_enabled = response['Reservations'][0]['Instances'][0].get('EnaSupport', False)
🔍 Interviewer Notes: Testing high-performance networking configuration.
❌ Common Mistakes:
- Using instance types that don't support Enhanced Networking
- Not installing ENA driver on custom AMIs
- Disabling ENA support accidentally
Q44: What is Elastic Fabric Adapter (EFA) and when to use it?
Technical Answer: EFA is a network interface for EC2 that provides low-latency, high-throughput communication for HPC and machine learning workloads. It uses OS-bypass technology to reduce latency between instances in a cluster placement group.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance with EFA enabled
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.24xlarge', # Supports EFA
MinCount=1,
MaxCount=1,
NetworkInterfaces=[{
'DeviceIndex': 0,
'AssociatePublicIpAddress': False,
'Groups': ['sg-hpc-security-group'],
'InterfaceType': 'efa' # Enable EFA
}],
Placement={'GroupName': 'hpc-cluster'} # EFA requires cluster placement group
)
🔍 Interviewer Notes: Testing HPC and ML networking requirements.
❌ Common Mistakes:
- Using EFA without cluster placement group
- Using EFA for non-HPC workloads
- Not installing EFA drivers on the OS
Q45: How do you configure EC2 for IPv6?
Technical Answer: EC2 instances can be assigned IPv6 addresses in VPCs that have IPv6 CIDR blocks associated. IPv6 addresses are globally unique and do not require NAT for internet access.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Assign IPv6 address to existing ENI
ec2.assign_ipv6_addresses(
NetworkInterfaceId='eni-1234567890abcdef0',
Ipv6Addresses=['2001:db8:1234:5678::100']
)
# Launch instance with IPv6
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
NetworkInterfaces=[{
'DeviceIndex': 0,
'SubnetId': 'subnet-ipv6-enabled',
'Ipv6Addresses': [{'Ipv6Address': '2001:db8:1234:5678::100'}]
}]
)
🔍 Interviewer Notes: Testing IPv6 networking configuration.
❌ Common Mistakes:
- Using IPv6 in VPCs without IPv6 CIDR blocks
- Forgetting to update security groups for IPv6 rules
- Not configuring IPv6 routes in route tables
Q46: What are EC2 networking limits and how do you work with them?
Technical Answer:
EC2 instances have limits on the number of ENIs, private IPs per ENI, and bandwidth based on instance type. Use describe_instance_types to check limits and select appropriate instance sizes for networking-heavy workloads.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Check networking limits for instance types
response = ec2.describe_instance_types(
InstanceTypes=['m5.large', 'c6i.4xlarge']
)
for instance in response['InstanceTypes']:
eni_info = instance.get('NetworkInfo', {})
print(f"{instance['InstanceType']}: Max ENIs: {eni_info.get('MaximumNetworkInterfaces', 'N/A')}")
print(f"Max private IPs per ENI: {eni_info.get('MaximumPrivateIpAddresses', 'N/A')}")
🔍 Interviewer Notes: Testing instance limit awareness for networking workloads.
❌ Common Mistakes:
- Exceeding max ENI count for an instance type
- Using smaller instances for network-intensive workloads
- Not requesting limit increases when needed
Q47: How do you use EC2 with VPC endpoints?
Technical Answer: VPC endpoints (Interface or Gateway) allow EC2 instances to access AWS services (S3, DynamoDB, etc.) without traversing the internet, improving security and reducing NAT costs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create Interface VPC endpoint for S3
endpoint = ec2.create_vpc_endpoint(
VpcId='vpc-123456',
ServiceName='com.amazonaws.us-east-1.s3',
VpcEndpointType='Interface',
SubnetIds=['subnet-123456'],
SecurityGroupIds=['sg-123456']
)
# EC2 instances in the subnet can now access S3 via the endpoint
# No internet gateway or NAT required
🔍 Interviewer Notes: Testing private connectivity to AWS services.
❌ Common Mistakes:
- Using Gateway endpoints for services that require Interface endpoints
- Forgetting to update security groups for endpoint access
- Not using endpoints for cross-region service access
Q48: What is EC2 instance metadata service version 2 (IMDSv2)?
Technical Answer: IMDSv2 is a more secure version of the instance metadata service that requires a session token to access, preventing SSRF attacks. All new instances should use IMDSv2, and IMDSv1 should be disabled where possible.
Code/Config Example:
import boto3
import requests
# Get IMDSv2 session token
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=5
).text
# Access metadata with token
instance_id = requests.get(
'http://169.254.169.254/latest/meta-data/instance-id',
headers={'X-aws-ec2-metadata-token': token},
timeout=5
).text
# Enforce IMDSv2 on new instances
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
MetadataOptions={
'HttpTokens': 'required', # Enforce IMDSv2
'HttpEndpoint': 'enabled',
'HttpPutResponseHopLimit': 2
}
)
🔍 Interviewer Notes: Testing security best practices for instance metadata.
❌ Common Mistakes:
- Using IMDSv1 (vulnerable to SSRF)
- Not configuring token TTL properly
- Disabling IMDS entirely (breaks instance functionality)
Q49: How do you configure EC2 for dual-homed networking?
Technical Answer: Dual-homed EC2 instances have two ENIs attached: one in a public subnet (internet access) and one in a private subnet (internal resources). This isolates public and private traffic for security.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create public ENI (eth0)
public_eni = ec2.create_network_interface(
SubnetId='subnet-public',
Groups=['sg-public'],
AssociatePublicIpAddress=True
)
# Create private ENI (eth1)
private_eni = ec2.create_network_interface(
SubnetId='subnet-private',
Groups=['sg-private']
)
# Launch instance with dual ENIs
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
NetworkInterfaces=[
{'DeviceIndex': 0, 'NetworkInterfaceId': public_eni['NetworkInterface']['NetworkInterfaceId']},
{'DeviceIndex': 1, 'NetworkInterfaceId': private_eni['NetworkInterface']['NetworkInterfaceId']}
]
)
🔍 Interviewer Notes: Testing network isolation and multi-homed configuration.
❌ Common Mistakes:
- Assigning public IPs to private ENIs
- Not configuring OS routing tables for dual ENIs
- Using same security group for both ENIs
Q50: What are EC2 Network Load Balancer (NLB) integration steps?
Technical Answer: NLB operates at Layer 4 (TCP/UDP) and can route traffic to EC2 instances in private subnets, supporting static IPs and high throughput. Register EC2 instances as targets in an NLB target group.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
# Create NLB
nlb = elbv2.create_load_balancer(
Name='app-nlb',
Subnets=['subnet-public-1a', 'subnet-public-1b'],
Scheme='internet-facing',
Type='network'
)
# Create target group
tg = elbv2.create_target_group(
Name='ec2-nlb-tg',
Protocol='TCP',
Port=80,
VpcId='vpc-123456',
HealthCheckProtocol='TCP'
)
# Register EC2 instances
elbv2.register_targets(
TargetGroupArn=tg['TargetGroups'][0]['TargetGroupArn'],
Targets=[
{'Id': 'i-1234567890abcdef0', 'Port': 80},
{'Id': 'i-0987654321fedcba0', 'Port': 80}
]
)
🔍 Interviewer Notes: Testing Layer 4 load balancing configuration.
❌ Common Mistakes:
- Using NLB for Layer 7 (HTTP) workloads (use ALB instead)
- Not using static IPs for NLB when required
- Forgetting to configure health checks
Q51: How do you create and manage EC2 launch templates?
Technical Answer: Launch templates define instance configuration (AMI, instance type, security groups, etc.) for EC2 Auto Scaling, Spot Fleet, and EC2 Fleet. They support versioning and are preferred over launch configurations.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create launch template
lt = ec2.create_launch_template(
LaunchTemplateName='web-server-template',
LaunchTemplateData={
'ImageId': 'ami-0123456789abcdef0',
'InstanceType': 't3.medium',
'KeyName': 'my-key-pair',
'SecurityGroupIds': ['sg-123456'],
'IamInstanceProfile': {'Name': 'EC2-SSM-Role'},
'UserData': 'IyEvYmluL2Jhc2gK...' # Base64 encoded user data
}
)
# Create new version of launch template
ec2.create_launch_template_version(
LaunchTemplateId=lt['LaunchTemplate']['LaunchTemplateId'],
SourceVersion='1',
LaunchTemplateData={'InstanceType': 't3.large'}
)
🔍 Interviewer Notes: Testing infrastructure as code and reusable instance configuration.
❌ Common Mistakes:
- Using launch configurations instead of launch templates
- Not versioning launch templates
- Hardcoding values instead of using parameters
Q52: What are EC2 Auto Scaling lifecycle hooks?
Technical Answer: Lifecycle hooks pause Auto Scaling instances during launch or terminate transitions, allowing custom actions (e.g., installing software, draining connections) before the instance enters the next state.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
# Add lifecycle hook to Auto Scaling group
autoscaling.put_lifecycle_hook(
AutoScalingGroupName='web-asg',
LifecycleHookName='pre-terminate-hook',
LifecycleTransition='autoscaling:EC2_INSTANCE_TERMINATING',
HeartbeatTimeout=3600, # 1 hour to complete action
DefaultResult='ABANDON' # If no response, abandon instance
)
# Complete lifecycle action after custom work
autoscaling.complete_lifecycle_action(
LifecycleHookName='pre-terminate-hook',
AutoScalingGroupName='web-asg',
LifecycleActionToken='token-123',
LifecycleActionResult='CONTINUE'
)
🔍 Interviewer Notes: Testing custom Auto Scaling workflows.
❌ Common Mistakes:
- Setting heartbeat timeout too short
- Not handling lifecycle hook timeouts
- Forgetting to complete lifecycle actions
Q53: How do you configure Auto Scaling scheduled scaling?
Technical Answer: Scheduled scaling adjusts Auto Scaling group capacity based on predictable time-based patterns (e.g., increased capacity during business hours, reduced at night).
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
# Scheduled action for business hours (scale out at 8 AM UTC)
autoscaling.put_scheduled_update_group_action(
AutoScalingGroupName='web-asg',
ScheduledActionName='scale-out-morning',
Recurrence='0 8 * * MON-FRI', # Cron expression
MinSize=5,
MaxSize=15,
DesiredCapacity=10
)
# Scheduled action to scale in at night
autoscaling.put_scheduled_update_group_action(
AutoScalingGroupName='web-asg',
ScheduledActionName='scale-in-evening',
Recurrence='0 18 * * MON-FRI',
DesiredCapacity=2
)
🔍 Interviewer Notes: Testing time-based scaling strategies.
❌ Common Mistakes:
- Using incorrect cron expressions
- Not considering time zones
- Conflicting scheduled actions
Q54: What is EC2 Auto Scaling predictive scaling?
Technical Answer: Predictive scaling uses machine learning to forecast future traffic and proactively adjust capacity, reducing the lag between traffic increases and scaling responses.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.put_scaling_policy(
AutoScalingGroupName='web-asg',
PolicyName='predictive-scaling-policy',
PolicyType='PredictiveScaling',
PredictiveScalingConfiguration={
'MetricSpecification': {
'TargetValue': 50.0,
'PredefinedLoadMetricSpecification': {
'PredefinedMetricType': 'ASGTotalCPUUtilization'
},
'PredefinedScalingMetricSpecification': {
'PredefinedMetricType': 'ASGAverageCPUUtilization'
}
},
'Mode': 'ForecastAndScale', # Or 'ForecastOnly'
'SchedulingBufferTime': 10
}
)
🔍 Interviewer Notes: Testing proactive scaling strategies.
❌ Common Mistakes:
- Using predictive scaling for unpredictable workloads
- Not validating forecasts before enabling ForecastAndScale
- Conflicting with target tracking policies
Q55: How do you use mixed instances policies in Auto Scaling?
Technical Answer: Mixed instances policies allow Auto Scaling groups to launch multiple instance types and sizes from a single launch template, improving availability and Spot cost optimization.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='mixed-asg',
MixedInstancesPolicy={
'LaunchTemplate': {
'LaunchTemplateId': 'lt-1234567890abcdef0',
'Version': '$Latest'
},
'InstancesDistribution': {
'OnDemandPercentageAboveBaseCapacity': 30,
'SpotAllocationStrategy': 'capacity-optimized',
'SpotMaxPrice': '0.10'
}
},
MinSize=2,
MaxSize=20
)
🔍 Interviewer Notes: Testing flexible instance provisioning.
❌ Common Mistakes:
- Not diversifying instance types enough
- Using wrong Spot allocation strategy
- Not setting base capacity for On-Demand
Q56: What are EC2 Auto Scaling warm pools?
Technical Answer: Warm pools maintain pre-initialized instances in a stopped, hibernated, or running state, reducing scale-out latency when traffic increases.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.put_warm_pool(
AutoScalingGroupName='web-asg',
PoolState='Stopped', # or 'Hibernated', 'Running'
MinSize=2,
MaxGroupPreparedCapacity=10
)
# Pre-initialized instances are ready to start in seconds
🔍 Interviewer Notes: Testing scale-out latency optimization.
❌ Common Mistakes:
- Using Running state for warm pools (higher cost)
- Not configuring instance reuse
- Setting warm pool size too large
Q57: How do you configure Auto Scaling instance refresh?
Technical Answer: Instance refresh gradually replaces all instances in an Auto Scaling group with a new launch template version, enabling zero-downtime updates to instance configuration.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.start_instance_refresh(
AutoScalingGroupName='web-asg',
Preferences={
'MinHealthyPercentage': 90, # Keep 90% healthy during refresh
'InstanceWarmup': 300, # Wait 5 min after instance starts
'CheckpointPercentages': [20, 50, 80],
'CheckpointDelay': 600
}
)
🔍 Interviewer Notes: Testing rolling updates for Auto Scaling groups.
❌ Common Mistakes:
- Setting MinHealthyPercentage too low (causes downtime)
- Not monitoring instance refresh status
- Starting refresh during peak traffic
Q58: What are EC2 Auto Scaling termination policies?
Technical Answer: Termination policies control which instances are terminated first during scale-in, such as oldest instance, closest to next billing hour, or allocation strategy (for Spot instances).
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='web-asg',
TerminationPolicies=[
'OldestLaunchTemplate', # Terminate instances with oldest launch template first
'Default' # Then default policy
],
# ... other ASG config
)
🔍 Interviewer Notes: Testing cost optimization during scale-in.
❌ Common Mistakes:
- Using wrong termination policy for workload
- Not prioritizing Spot instance termination
- Terminating newest instances first (disrupts workloads)
Q59: How do you integrate Auto Scaling with Elastic Load Balancing?
Technical Answer: Auto Scaling groups register instances with ELB target groups, and ELB health checks can be used to replace unhealthy instances automatically.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='web-asg',
TargetGroupARNs=['arn:aws:elasticloadbalancing:us-east-1:123456789:targetgroup/web-tg/123456'],
HealthCheckType='ELB', # Use ELB health checks instead of EC2
HealthCheckGracePeriod=300,
# ... other ASG config
)
🔍 Interviewer Notes: Testing high availability integration.
❌ Common Mistakes:
- Using EC2 health checks instead of ELB for web workloads
- Not setting health check grace period
- Forgetting to register target groups
Q60: What are EC2 Auto Scaling health check types?
Technical Answer: Auto Scaling supports EC2 health checks (instance status) and ELB health checks (application status). ELB health checks detect application-level failures, while EC2 checks detect underlying hardware issues.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
# EC2 health check (default)
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='backend-asg',
HealthCheckType='EC2',
# ... other config
)
# ELB health check (for web workloads)
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='web-asg',
HealthCheckType='ELB',
TargetGroupARNs=['arn:aws:elasticloadbalancing:...:targetgroup/web-tg'],
HealthCheckGracePeriod=300
)
🔍 Interviewer Notes: Testing health check configuration for different workloads.
❌ Common Mistakes:
- Using EC2 health checks for application failures
- Not setting grace period for ELB health checks
- Confusing health check types
Q61: How do you integrate EC2 with Application Load Balancer (ALB)?
Technical Answer: ALB routes HTTP/HTTPS traffic to EC2 instances in target groups, supporting path/host-based routing and sticky sessions. Register EC2 instances as targets in ALB target groups for Layer 7 load balancing.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
# Create ALB
alb = elbv2.create_load_balancer(
Name='web-alb',
Subnets=['subnet-123', 'subnet-456'],
SecurityGroups=['sg-web'],
Scheme='internet-facing',
Type='application'
)
# Create target group for EC2 instances
tg = elbv2.create_target_group(
Name='ec2-web-tg',
Protocol='HTTP',
Port=80,
VpcId='vpc-123',
HealthCheckPath='/health'
)
# Register EC2 instances
elbv2.register_targets(
TargetGroupArn=tg['TargetGroups'][0]['TargetGroupArn'],
Targets=[
{'Id': 'i-1234567890abcdef0', 'Port': 80},
{'Id': 'i-0987654321fedcba0', 'Port': 80}
]
)
🔍 Interviewer Notes: Testing Layer 7 load balancing configuration.
❌ Common Mistakes:
- Using ALB for TCP workloads (use NLB instead)
- Not configuring health check endpoints
- Forgetting to register instances with target groups
Q62: What are ALB path-based routing rules for EC2 targets?
Technical Answer: ALB supports path-based routing to direct traffic to different EC2 target groups based on URL paths (e.g., /api/_ to backend instances, /images/_ to static servers).
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
# Create listener rule for path-based routing
elbv2.create_rule(
ListenerArn='arn:aws:elasticloadbalancing:...:listener/app/web-alb/123',
Conditions=[
{'Field': 'path-pattern', 'Values': ['/api/*']}
],
Actions=[
{'Type': 'forward', 'TargetGroupArn': 'arn:aws:elasticloadbalancing:...:targetgroup/backend-tg'}
],
Priority=10
)
🔍 Interviewer Notes: Testing advanced ALB routing configuration.
❌ Common Mistakes:
- Overlapping path patterns
- Incorrect priority values
- Not testing routing rules
Q63: How do you configure ALB health checks for EC2 instances?
Technical Answer: ALB health checks verify EC2 instance application health by sending HTTP/HTTPS requests to a configured path. Unhealthy instances are automatically removed from rotation.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
elbv2.create_target_group(
Name='web-tg',
Protocol='HTTP',
Port=80,
VpcId='vpc-123',
HealthCheckProtocol='HTTP',
HealthCheckPath='/health',
HealthCheckIntervalSeconds=30,
HealthCheckTimeoutSeconds=5,
HealthyThresholdCount=2,
UnhealthyThresholdCount=3
)
🔍 Interviewer Notes: Testing application health monitoring.
❌ Common Mistakes:
- Health check path returning 500 errors
- Too short timeout for slow-starting apps
- Not matching health check port to instance listener
Q64: What is connection draining for ELB with EC2?
Technical Answer: Connection draining (deregistration delay) allows EC2 instances to complete in-flight requests before being deregistered from load balancers during scale-in or deployments.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
elbv2.modify_target_group_attributes(
TargetGroupArn='arn:aws:elasticloadbalancing:...:targetgroup/web-tg',
Attributes=[
{'Key': 'deregistration_delay.timeout_seconds', 'Value': '300'}
]
)
🔍 Interviewer Notes: Testing zero-downtime deployment practices.
❌ Common Mistakes:
- Setting deregistration delay too short
- Not enabling connection draining for stateful apps
- Forgetting to handle SIGTERM in applications
Q65: How do you use EC2 with Gateway Load Balancer (GWLB)?
Technical Answer: GWLB operates at Layer 3 to distribute traffic to third-party network appliances (firewalls, IDS/IPS) running on EC2 instances. It uses GENEVE tunneling to forward traffic to appliance instances.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
# Create GWLB
gwlb = elbv2.create_load_balancer(
Name='firewall-gwlb',
Subnets=['subnet-123'],
Scheme='internal',
Type='gateway'
)
# Create target group for appliance instances
tg = elbv2.create_target_group(
Name='firewall-tg',
Protocol='GENEVE',
Port=6081,
VpcId='vpc-123'
)
🔍 Interviewer Notes: Testing network appliance integration.
❌ Common Mistakes:
- Using GWLB for standard web workloads
- Not configuring GENEVE tunneling on appliances
- Missing route table entries for GWLB endpoints
Q66: How do you configure ELB security groups for EC2?
Technical Answer: ELB security groups must allow inbound traffic from clients, and outbound traffic to EC2 instances. EC2 security groups must allow inbound traffic from ELB security groups, not directly from clients.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# ELB security group
elb_sg = ec2.create_security_group(
GroupName='elb-sg',
Description='Allow client traffic to ELB',
VpcId='vpc-123'
)
ec2.authorize_security_group_ingress(
GroupId=elb_sg['GroupId'],
IpPermissions=[{'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}]
)
# EC2 security group
ec2_sg = ec2.create_security_group(
GroupName='ec2-sg',
Description='Allow traffic from ELB only',
VpcId='vpc-123'
)
ec2.authorize_security_group_ingress(
GroupId=ec2_sg['GroupId'],
IpPermissions=[{'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'UserIdGroupPairs': [{'GroupId': elb_sg['GroupId']}]}]
)
🔍 Interviewer Notes: Testing security group chaining for load balancers.
❌ Common Mistakes:
- Allowing direct client access to EC2 instances
- Not referencing ELB security group in EC2 SG
- Opening 0.0.0.0/0 on EC2 instances
Q67: What are ELB access logs for EC2 troubleshooting?
Technical Answer: ELB access logs capture detailed request information (client IP, request path, response code) to S3 for troubleshooting and analytics. Enable access logs on ALB/NLB to debug EC2 traffic issues.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
elbv2.modify_load_balancer_attributes(
LoadBalancerArn='arn:aws:elasticloadbalancing:...:loadbalancer/app/web-alb/123',
Attributes=[
{'Key': 'access_logs.s3.enabled', 'Value': 'true'},
{'Key': 'access_logs.s3.bucket', 'Value': 'elb-access-logs-bucket'},
{'Key': 'access_logs.s3.prefix', 'Value': 'web-alb-logs'}
]
)
🔍 Interviewer Notes: Testing observability for load-balanced workloads.
❌ Common Mistakes:
- Not enabling access logs
- S3 bucket permissions misconfigured
- Not analyzing logs for 5xx errors
Q68: How do you enable cross-zone load balancing for EC2?
Technical Answer: Cross-zone load balancing distributes traffic evenly across EC2 instances in all enabled AZs, improving availability. Enable for ALB (default enabled) and NLB (disabled by default) to avoid imbalanced traffic.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
elbv2.modify_load_balancer_attributes(
LoadBalancerArn='arn:aws:elasticloadbalancing:...:loadbalancer/net/web-nlb/123',
Attributes=[
{'Key': 'load_balancing.cross_zone.enabled', 'Value': 'true'}
]
)
🔍 Interviewer Notes: Testing high availability configuration.
❌ Common Mistakes:
- Not enabling cross-zone for NLB
- Unbalanced instance counts across AZs
- Not considering AZ latency
Q69: What is ELB sticky sessions for EC2 targets?
Technical Answer: Sticky sessions (session affinity) bind client sessions to specific EC2 instances using cookies, useful for stateful applications that don't use shared session stores.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
elbv2.modify_target_group_attributes(
TargetGroupArn='arn:aws:elasticloadbalancing:...:targetgroup/web-tg',
Attributes=[
{'Key': 'stickiness.enabled', 'Value': 'true'},
{'Key': 'stickiness.type', 'Value': 'lb_cookie'},
{'Key': 'stickiness.lb_cookie.duration_seconds', 'Value': '86400'}
]
)
🔍 Interviewer Notes: Testing stateful application load balancing.
❌ Common Mistakes:
- Using sticky sessions for stateless apps
- Long cookie duration causing imbalanced load
- Not migrating to shared session stores
Q70: How do you use EC2 with internal vs internet-facing ELB?
Technical Answer: Internet-facing ELBs have public IPs and accept traffic from the internet, while internal ELBs have private IPs and only accept VPC/internal traffic. Use internal ELBs for backend services and internet-facing for public web apps.
Code/Config Example:
import boto3
elbv2 = boto3.client('elbv2')
# Internet-facing ELB for public web
public_elb = elbv2.create_load_balancer(
Name='public-web-alb',
Subnets=['subnet-public-1a', 'subnet-public-1b'],
Scheme='internet-facing',
Type='application'
)
# Internal ELB for backend APIs
internal_elb = elbv2.create_load_balancer(
Name='internal-api-alb',
Subnets=['subnet-private-1a', 'subnet-private-1b'],
Scheme='internal',
Type='application'
)
🔍 Interviewer Notes: Testing public/private workload separation.
❌ Common Mistakes:
- Using internet-facing ELB for backend services
- Not configuring route tables for internal ELBs
- Mixing public/private subnets for internal ELBs
Q71: How do you assign IAM roles to EC2 instances?
Technical Answer: IAM roles are assigned to EC2 instances via instance profiles, providing temporary AWS credentials without long-term access keys. Attach IAM roles during instance launch or by associating an instance profile to running instances.
Code/Config Example:
import boto3
iam = boto3.client('iam')
ec2 = boto3.client('ec2')
# Create IAM role for EC2
iam.create_role(
RoleName='ec2-s3-read-role',
AssumeRolePolicyDocument=json.dumps({
'Version': '2012-10-17',
'Statement': [{'Effect': 'Allow', 'Principal': {'Service': 'ec2.amazonaws.com'}, 'Action': 'sts:AssumeRole'}]
})
)
# Create instance profile and add role
iam.create_instance_profile(InstanceProfileName='ec2-s3-read-profile')
iam.add_role_to_instance_profile(
InstanceProfileName='ec2-s3-read-profile',
RoleName='ec2-s3-read-role'
)
# Launch instance with IAM role
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='t3.medium',
IamInstanceProfile={'Name': 'ec2-s3-read-profile'}
)
🔍 Interviewer Notes: Testing secure credential management for EC2.
❌ Common Mistakes:
- Using long-term access keys instead of IAM roles
- Not adding role to instance profile
- Overly permissive IAM policies
Q72: What is EC2 instance profiles and how do they work?
Technical Answer: Instance profiles are containers for IAM roles that can be attached to EC2 instances. They act as the bridge between IAM roles and EC2 instances, allowing the instance to retrieve temporary credentials via IMDS.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# List instance profiles
profiles = iam.list_instance_profiles()
for profile in profiles['InstanceProfiles']:
print(f"Profile: {profile['InstanceProfileName']}, Roles: {[r['RoleName'] for r in profile['Roles']]}")
# Remove role from instance profile
iam.remove_role_from_instance_profile(
InstanceProfileName='ec2-s3-read-profile',
RoleName='ec2-s3-read-role'
)
🔍 Interviewer Notes: Testing IAM instance profile concepts.
❌ Common Mistakes:
- Confusing instance profiles with IAM roles
- Attaching multiple roles to one instance profile
- Not waiting for profile propagation
Q73: How do you rotate IAM credentials for EC2 instances?
Technical Answer: IAM roles for EC2 automatically rotate temporary credentials every few hours. No manual rotation is needed; applications retrieve fresh credentials from IMDS automatically when using AWS SDKs.
Code/Config Example:
import boto3
import requests
# Get fresh credentials from IMDSv2
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'}
).text
creds = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/ec2-s3-read-role',
headers={'X-aws-ec2-metadata-token': token}
).json()
# Use credentials (SDK does this automatically)
s3 = boto3.client(
's3',
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['Token']
)
🔍 Interviewer Notes: Testing automatic credential rotation.
❌ Common Mistakes:
- Hardcoding temporary credentials
- Not using SDK default credential provider chain
- Manually rotating IAM role credentials
Q74: What are IAM role best practices for EC2?
Technical Answer:
Follow least privilege by granting only required permissions, use managed policies over inline policies, and rotate IAM roles regularly. Avoid attaching overly permissive policies like AdministratorAccess to EC2 instances.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# Attach least privilege managed policy
iam.attach_role_policy(
RoleName='ec2-s3-read-role',
PolicyArn='arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
)
# Create custom least privilege policy
iam.put_role_policy(
RoleName='ec2-s3-read-role',
PolicyName='s3-bucket-specific',
PolicyDocument=json.dumps({
'Version': '2012-10-17',
'Statement': [{'Effect': 'Allow', 'Action': 's3:GetObject', 'Resource': 'arn:aws:s3:::my-bucket/*'}]
})
)
🔍 Interviewer Notes: Testing least privilege implementation.
❌ Common Mistakes:
- Using AdministratorAccess for EC2 roles
- Inline policies instead of managed policies
- Not auditing IAM role permissions
Q75: How do you use EC2 with SSM instance profiles?
Technical Answer:
SSM instance profiles allow EC2 instances to communicate with Systems Manager without SSH. Attach the AmazonSSMManagedInstanceCore managed policy to EC2 IAM roles to enable SSM access.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# Attach SSM policy to EC2 role
iam.attach_role_policy(
RoleName='ec2-ssm-role',
PolicyArn='arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
)
# Launch instance with SSM role
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='t3.medium',
IamInstanceProfile={'Name': 'ec2-ssm-profile'}
)
# Connect via SSM (no SSH key needed)
# aws ssm start-session --target i-1234567890abcdef0
🔍 Interviewer Notes: Testing SSH-less instance management.
❌ Common Mistakes:
- Not installing SSM agent on the OS
- Missing SSM policy in IAM role
- Using SSH keys when SSM is available
Q76: What is EC2 IAM pass role permission?
Technical Answer:
The iam:PassRole permission allows IAM principals to pass IAM roles to EC2 instances. This is required when launching instances with IAM roles via the API or CloudFormation.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# Policy granting PassRole permission
iam.put_user_policy(
UserName='deploy-user',
PolicyName='pass-ec2-role',
PolicyDocument=json.dumps({
'Version': '2012-10-17',
'Statement': [{
'Effect': 'Allow',
'Action': 'iam:PassRole',
'Resource': 'arn:aws:iam::123456789:role/ec2-s3-read-role'
}]
})
)
🔍 Interviewer Notes: Testing secure role delegation.
❌ Common Mistakes:
- Granting PassRole for all roles (*)
- Not scoping PassRole to specific roles
- Confusing PassRole with AssumeRole
Q77: How do you restrict EC2 IAM roles to specific resources?
Technical Answer: Use IAM policy conditions and resource ARNs to restrict EC2 IAM roles to specific S3 buckets, DynamoDB tables, or other AWS resources. Avoid using wildcard (*) in resource ARNs when possible.
Code/Config Example:
import boto3
iam = boto3.client('iam')
iam.put_role_policy(
RoleName='ec2-app-role',
PolicyName='restrict-s3-access',
PolicyDocument=json.dumps({
'Version': '2012-10-17',
'Statement': [{
'Effect': 'Allow',
'Action': 's3:GetObject',
'Resource': [
'arn:aws:s3:::app-assets-bucket/*',
'arn:aws:s3:::app-config-bucket/*'
]
}]
})
)
🔍 Interviewer Notes: Testing resource-level permissions.
❌ Common Mistakes:
- Using wildcard resources in production
- Not scoping permissions to specific resources
- Overly permissive IAM policies
Q78: What are EC2 instance identity roles?
Technical Answer: Instance identity roles are automatically created by some AWS services (like EMR, Batch) to grant EC2 instances permissions to interact with those services. They are managed by AWS and should not be modified manually.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# List roles (look for AWS service-created roles)
roles = iam.list_roles()
for role in roles['Roles']:
if 'aws-service-role' in role['Arn']:
print(f"Service role: {role['RoleName']}")
🔍 Interviewer Notes: Testing AWS managed service role knowledge.
❌ Common Mistakes:
- Modifying service-created instance identity roles
- Deleting service-created roles
- Confusing service roles with custom roles
Q79: How do you use EC2 with temporary security credentials?
Technical Answer: EC2 instances retrieve temporary credentials from IMDS (instance metadata service) automatically when using AWS SDKs. These credentials are rotated automatically and valid for up to 6 hours.
Code/Config Example:
import boto3
import requests
# SDK automatically uses IMDS credentials
s3 = boto3.client('s3')
response = s3.list_buckets() # Uses IMDS credentials
# Manual credential retrieval (for custom apps)
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'}
).text
creds = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/',
headers={'X-aws-ec2-metadata-token': token}
).json()
🔍 Interviewer Notes: Testing temporary credential usage.
❌ Common Mistakes:
- Hardcoding long-term credentials in apps
- Not using default credential provider chain
- Caching temporary credentials too long
Q80: What is EC2 IAM role for cross-account access?
Technical Answer:
EC2 instances in one account can access resources in another account by assuming a cross-account IAM role. The EC2 instance's IAM role needs sts:AssumeRole permission for the target account's role.
Code/Config Example:
import boto3
# EC2 instance role policy (account A)
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::TARGET_ACCOUNT_ID:role/cross-account-s3-role"
}]
}
# Assume cross-account role from EC2
sts = boto3.client('sts')
assumed_role = sts.assume_role(
RoleArn='arn:aws:iam::TARGET_ACCOUNT_ID:role/cross-account-s3-role',
RoleSessionName='ec2-cross-account-session'
)
# Use assumed role credentials
s3 = boto3.client(
's3',
aws_access_key_id=assumed_role['Credentials']['AccessKeyId'],
aws_secret_access_key=assumed_role['Credentials']['SecretAccessKey'],
aws_session_token=assumed_role['Credentials']['SessionToken']
)
🔍 Interviewer Notes: Testing cross-account access patterns.
❌ Common Mistakes:
- Not configuring trust policy on target role
- Missing sts:AssumeRole permission
- Not handling credential expiration
Q81: What are EC2 placement groups advanced use cases?
Technical Answer: Cluster placement groups are used for HPC/low latency (same rack), spread for fault isolation (separate hardware), and partition for distributed systems (isolated partitions). Each has specific limits and use cases.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Cluster placement group (low latency HPC)
ec2.create_placement_group(GroupName='hpc-cluster', Strategy='cluster')
# Launch HPC instances
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.24xlarge',
Placement={'GroupName': 'hpc-cluster'},
EnaSupport=True
)
# Spread placement group (fault isolation)
ec2.create_placement_group(GroupName='critical-apps', Strategy='spread')
🔍 Interviewer Notes: Testing advanced placement strategies.
❌ Common Mistakes:
- Using cluster for non-HPC workloads
- Exceeding 7 instances per AZ for spread
- Not using enhanced networking with cluster
Q82: How do you configure EC2 spread placement groups?
Technical Answer: Spread placement groups place instances on distinct hardware to reduce correlated failures. Max 7 instances per AZ per group, ideal for critical applications needing maximum fault isolation.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.create_placement_group(
GroupName='critical-spread',
Strategy='spread'
)
# Launch instances across spread group
for i in range(7):
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m6i.large',
MinCount=1,
MaxCount=1,
Placement={'GroupName': 'critical-spread'}
)
🔍 Interviewer Notes: Testing fault tolerance configuration.
❌ Common Mistakes:
- Exceeding 7 instances per AZ limit
- Using spread for burstable workloads
- Not spreading across AZs
Q83: What are EC2 partition placement groups?
Technical Answer: Partition placement groups divide instances into logical partitions (max 7 per AZ) where each partition has its own set of hardware. Ideal for HDFS, Cassandra, Kafka distributed systems.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.create_placement_group(
GroupName='distributed-storage',
Strategy='partition',
PartitionCount=3
)
# Launch instances into specific partition
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='r6i.2xlarge',
Placement={
'GroupName': 'distributed-storage',
'PartitionNumber': 1
}
)
🔍 Interviewer Notes: Testing distributed system placement.
❌ Common Mistakes:
- Using too few/many partitions
- Not matching partitions to application topology
- Exceeding partition limits
Q84: How do you use EC2 dedicated hosts for BYOL?
Technical Answer: Dedicated Hosts allow Bring Your Own License (BYOL) for software licensed per socket/core. You get full visibility into host socket/core count to comply with license terms.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Allocate dedicated host for BYOL
host = ec2.allocate_hosts(
InstanceType='m5.large',
Quantity=1,
AvailabilityZone='us-east-1a'
)
# Launch instance on host with BYOL
ec2.run_instances(
ImageId='ami-byol-image',
InstanceType='m5.large',
Placement={
'Tenancy': 'host',
'HostId': host['HostIds'][0]
}
)
🔍 Interviewer Notes: Testing license compliance.
❌ Common Mistakes:
- Using dedicated instances instead of hosts for BYOL
- Not tracking license usage
- Over-provisioning host capacity
Q85: What are EC2 dedicated host restrictions?
Technical Answer: Dedicated Hosts are tied to specific instance families, cannot be resized, and require host recovery configuration. You pay for the entire host regardless of instance count running on it.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Describe host restrictions
response = ec2.describe_hosts(HostIds=['h-1234567890abcdef0'])
host = response['Hosts'][0]
print(f"Instance type: {host['InstanceType']}")
print(f"Available capacity: {host['AvailableCapacity']}")
🔍 Interviewer Notes: Testing dedicated host limitations.
❌ Common Mistakes:
- Expecting host resizing
- Launching wrong instance type on host
- Not enabling host recovery
Q86: How do you monitor EC2 dedicated host utilization?
Technical Answer:
Use CloudWatch metrics for dedicated hosts: HostCapacity', HostInstances', `HostReservationUtilization'. Monitor to ensure hosts are fully utilized to justify cost.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='HostInstances',
Dimensions=[{'Name': 'HostId', 'Value': 'h-1234567890abcdef0'}],
StartTime='2024-05-01T00:00:00Z',
EndTime='2024-05-01T23:59:59Z',
Period=3600,
Statistics=['Average']
)
🔍 Interviewer Notes: Testing host cost optimization.
❌ Common Mistakes:
- Not monitoring host utilization
- Underutilizing paid hosts
- Not releasing unused hosts
Q87: What are EC2 Nitro enclaves?
Technical Answer: Nitro Enclaves provide isolated compute environments for processing sensitive data (PII, passwords) with no persistent storage, interactive access, or external networking. Used with AWS KMS for envelope encryption.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance with Nitro Enclaves enabled
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.xlarge',
EnclaveOptions={'Enabled': True}
)
# Configure enclave allocator (on instance)
# nitro-enclaves-allocator.yaml: memory_mib: 1024, cpu_count: 2
🔍 Interviewer Notes: Testing advanced security isolation.
❌ Common Mistakes:
- Not enabling enclaves at launch
- Insufficient instance memory for enclave
- Not using KMS for enclave data
Q88: How do you use EC2 with AWS Outposts?
Technical Answer: AWS Outposts bring native AWS services (including EC2) to on-premises locations. Launch EC2 instances on Outposts using subnet with Outpost ID, with same AWS APIs and tools.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch EC2 instance on Outpost
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
SubnetId='subnet-outpost', # Subnet associated with Outpost
Placement={'Tenancy': 'dedicated'}
)
🔍 Interviewer Notes: Testing hybrid cloud EC2 usage.
❌ Common Mistakes:
- Using standard subnets for Outpost instances
- Not configuring local gateways
- Using instance types not supported on Outposts
Q89: What are EC2 Wavelength Zones?
Technical Answer: Wavelength Zones are AWS infrastructure deployed in telecom provider networks, bringing EC2 closer to mobile devices. Used for ultra-low latency applications (AR/VR, gaming) at the edge.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance in Wavelength Zone
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='t3.medium',
SubnetId='subnet-wavelength', # Wavelength Zone subnet
Placement={'AvailabilityZone': 'us-east-1-wl1'}
)
🔍 Interviewer Notes: Testing edge computing use cases.
❌ Common Mistakes:
- Using Wavelength for standard workloads
- Not configuring carrier IPs
- Insufficient latency requirements
Q90: How do you use EC2 with Local Zones?
Technical Answer: Local Zones are extensions of AWS regions in metropolitan areas, providing low latency to local users. Launch EC2 instances in Local Zones using zone-specific subnets.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enable Local Zone (if not already enabled)
ec2.modify_availability_zone_group(
GroupName='us-west-2-lax-1a',
OptInStatus='opted-in'
)
# Launch instance in Local Zone
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
SubnetId='subnet-local-zone',
Placement={'AvailabilityZone': 'us-west-2-lax-1a'}
)
🔍 Interviewer Notes: Testing low-latency local access.
❌ Common Mistakes:
- Not enabling Local Zones first
- Using Local Zones for non-latency sensitive workloads
- Missing local zone service support
Q91: How do you configure EC2 detailed monitoring?
Technical Answer: Detailed monitoring enables 1-minute CloudWatch metrics (vs default 5-minute) for EC2 instances. Enable during launch or modify existing instances; charges apply for detailed monitoring.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enable detailed monitoring at launch
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
Monitoring={'Enabled': True}
)
# Enable for existing instance
ec2.monitor_instances(InstanceIds=['i-1234567890abcdef0'])
🔍 Interviewer Notes: Testing metric granularity configuration.
❌ Common Mistakes:
- Not enabling detailed monitoring for critical apps
- Extra cost for detailed monitoring
- Using basic monitoring for auto scaling
Q92: What are EC2 CloudWatch custom metrics?
Technical Answer: Publish custom application metrics (queue length, error rates) to CloudWatch from EC2 instances using the CloudWatch agent or PutMetricData API. Enables alarms on application-specific thresholds.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_data(
Namespace='MyApp/EC2',
MetricData=[{
'MetricName': 'ActiveUsers',
'Value': 150,
'Unit': 'Count',
'Dimensions': [{'Name': 'InstanceId', 'Value': 'i-1234567890abcdef0'}]
}]
)
🔍 Interviewer Notes: Testing custom observability.
❌ Common Mistakes:
- Not setting appropriate dimensions
- High metric resolution without need
- Missing timestamps on metrics
Q93: How do you use EC2 Systems Manager Run Command?
Technical Answer: Run Command executes scripts/shell commands on EC2 instances without SSH, using SSM agent. Supports Linux/Windows, runs asynchronously, and returns output to CloudWatch Logs.
Code/Config Example:
import boto3
ssm = boto3.client('ssm')
response = ssm.send_command(
InstanceIds=['i-1234567890abcdef0'],
DocumentName='AWS-RunShellScript',
Parameters={
'commands': [
'df -h',
'free -m',
'uptime'
]
}
)
# Get command output
ssm.get_command_invocation(
CommandId=response['Command']['CommandId'],
InstanceId='i-1234567890abcdef0'
)
🔍 Interviewer Notes: Testing remote management without SSH.
❌ Common Mistakes:
- SSM agent not installed on instance
- IAM role missing SSM permissions
- Not checking command status
Q94: What is EC2 Systems Manager Patch Manager?
Technical Answer: Patch Manager automates OS and application patching for EC2 instances with configurable maintenance windows. Supports baseline patches, approval rules, and compliance reporting.
Code/Config Example:
import boto3
ssm = boto3.client('ssm')
# Send patch command
ssm.send_command(
InstanceIds=['i-1234567890abcdef0'],
DocumentName='AWS-RunPatchBaseline',
Parameters={
'Operation': ['Install'],
'RebootOption': ['RebootIfNeeded']
}
)
🔍 Interviewer Notes: Testing automated patch management.
❌ Common Mistakes:
- Not configuring patch baselines
- Patching during peak hours
- Not testing patches first
Q95: How do you use EC2 Systems Manager Parameter Store?
Technical Answer: Parameter Store provides secure hierarchical storage for configuration data, secrets, and strings. EC2 instances retrieve parameters via IAM role permissions, supports encryption with KMS.
Code/Config Example:
import boto3
ssm = boto3.client('ssm')
# Put parameter
ssm.put_parameter(
Name='/myapp/db/password',
Value='secret123',
Type='SecureString',
KeyId='arn:aws:kms:us-east-1:123456789:key/1234abcd'
)
# Get parameter from EC2 instance
response = ssm.get_parameter(
Name='/myapp/db/password',
WithDecryption=True
)
🔍 Interviewer Notes: Testing configuration management.
❌ Common Mistakes:
- Storing large values in Parameter Store
- Not encrypting sensitive parameters
- Missing IAM permissions to decrypt
Q96: What are EC2 Systems Manager documents?
Technical Answer: SSM documents define the actions SSM performs (shell scripts, PowerShell, automation steps). AWS provides managed documents, or create custom documents for specific workflows.
Code/Config Example:
import boto3
ssm = boto3.client('ssm')
# Create custom document
ssm.create_document(
Name='MyAppRestart',
DocumentType='Command',
Content=json.dumps({
'schemaVersion': '2.2',
'description': 'Restart my app service',
'mainSteps': [{
'action': 'aws:runShellScript',
'name': 'restartApp',
'inputs': {
'runCommand': ['systemctl restart myapp']
}
}]
})
)
🔍 Interviewer Notes: Testing automation workflow definition.
❌ Common Mistakes:
- Incorrect document schema version
- Not testing documents before use
- Overly complex documents
Q97: How do you monitor EC2 status checks?
Technical Answer: EC2 status checks monitor instance health: system status (AWS hardware/network) and instance status (OS/disk full). Failed checks trigger CloudWatch alarms for recovery actions.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
# Alarm for system status check failure
cloudwatch.put_metric_alarm(
AlarmName='ec2-system-status-failed',
MetricName='StatusCheckFailed_System',
Namespace='AWS/EC2',
Dimensions=[{'Name': 'InstanceId', 'Value': 'i-1234567890abcdef0'}],
Threshold=1,
ComparisonOperator='GreaterThanOrEqualToThreshold',
AlarmActions=['arn:aws:automate:us-east-1:ec2:recover']
)
🔍 Interviewer Notes: Testing instance health monitoring.
❌ Common Mistakes:
- Confusing system vs instance status checks
- Not setting recovery actions
- Ignoring status check failures
Q98: What are EC2 CloudWatch alarms best practices?
Technical Answer: Set appropriate thresholds, use multiple evaluation periods, configure actions (SNS, Auto Scaling), and test alarms regularly. Avoid alarm fatigue by setting meaningful thresholds.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_alarm(
AlarmName='ec2-cpu-high',
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistic='Average',
Period=300,
EvaluationPeriods=3, # Require 3 periods above threshold
Threshold=85,
ComparisonOperator='GreaterThanThreshold',
TreatMissingData='notBreaching'
)
🔍 Interviewer Notes: Testing alarm configuration best practices.
❌ Common Mistakes:
- Single evaluation period (flapping)
- Not handling missing data
- No actions configured
Q99: How do you use EC2 with CloudWatch Logs?
Technical Answer: CloudWatch Logs agent sends EC2 instance logs (application, system) to CloudWatch Logs for centralized logging. Configure log groups, streams, and retention policies.
Code/Config Example:
import boto3
logs = boto3.client('logs')
# Create log group
logs.create_log_group(
logGroupName='/ec2/web-server',
tags={'Environment': 'production'}
)
# Configure CloudWatch agent on instance to send /var/log/httpd/* to log group
🔍 Interviewer Notes: Testing centralized logging.
❌ Common Mistakes:
- Not setting log retention policies
- Sending verbose debug logs
- Missing IAM permissions for logs
Q100: What is EC2 Systems Manager Session Manager?
Technical Answer: Session Manager provides interactive shell access to EC2 instances without SSH keys, bastion hosts, or open ports. Uses IAM permissions, logs sessions to S3/CloudWatch Logs.
Code/Config Example:
# Start session via AWS CLI (no SSH needed)
aws ssm start-session --target i-1234567890abcdef0
# Instance requires SSM agent and IAM role with AmazonSSMManagedInstanceCore policy
🔍 Interviewer Notes: Testing SSH-less instance access.
❌ Common Mistakes:
- SSM agent not installed
- Missing IAM permissions
- Not logging session activity
2. Intermediate Topics
Q101: How do you implement EC2 image building automation?
Technical Answer: Use EC2 Image Builder for automated AMI creation.
import boto3
imagebuilder = boto3.client('imagebuilder')
# Create component (build step)
component = imagebuilder.create_component(
name='web-server-component',
version='1.0.0',
platform='Linux',
data='''
name: WebServerBuild
schemaVersion: 1.0
phases:
- name: build
steps:
- name: InstallHttpd
action: ExecuteBash
inputs:
commands:
- yum install -y httpd php
- systemctl enable httpd
- name: ConfigureApp
action: ExecuteBash
inputs:
commands:
- echo "<?php phpinfo(); ?>" > /var/www/html/index.php
'''
)
# Create recipe
recipe = imagebuilder.create_image_recipe(
name='web-server-recipe',
version='1.0.0',
components=[{'componentArn': component['componentBuildVersionArn']}],
parentImage='arn:aws:imagebuilder:us-east-1:aws:image/amazon-linux-2-x86/x.x.x'
)
# Create pipeline
pipeline = imagebuilder.create_image_pipeline(
name='web-server-pipeline',
imageRecipeArn=recipe['imageRecipeArn'],
infrastructureConfigurationArn='arn:aws:imagebuilder:...:infrastructure-configuration/web',
distributionConfigurationArn='arn:aws:imagebuilder:...:distribution-configuration/web',
schedule={'scheduleExpression': 'cron(0 0 ? * MON *)'}
)
🔍 Interviewer Notes: Testing automation and DevOps practices.
Q102: How do you implement EC2 placement strategies?
Technical Answer:
Placement Groups:
import boto3
ec2 = boto3.client('ec2')
# Cluster - low latency, high throughput
cluster_pg = ec2.create_placement_group(
GroupName='cluster-pg',
Strategy='cluster'
)
# Spread - separate hardware
spread_pg = ec2.create_placement_group(
GroupName='spread-pg',
Strategy='spread'
)
# Partition - multiple isolated groups
partition_pg = ec2.create_placement_group(
GroupName='partition-pg',
Strategy='partition',
PartitionCount=3
)
# Launch in placement group
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='c6i.24xlarge',
MinCount=1,
MaxCount=1,
Placement={'GroupName': 'cluster-pg'}
)
🔍 Interviewer Notes: Testing high-performance computing patterns.
Q103: How do you implement EC2 recovery mechanisms?
Technical Answer:
CloudWatch Alarms for Recovery:
import boto3
cloudwatch = boto3.client('cloudwatch')
# System status check alarm
cloudwatch.put_metric_alarm(
AlarmName='ec2-system-status-check',
AlarmDescription='Recover instance on system failure',
ActionsEnabled=True,
AlarmActions=['arn:aws:automate:us-east-1:ec2:recover'],
MetricName='StatusCheckFailed_System',
Namespace='AWS/EC2',
Statistic='Average',
Dimensions=[{'Name': 'InstanceId', 'Value': 'i-123456789'}],
Period=60,
EvaluationPeriods=2,
Threshold=1,
ComparisonOperator='GreaterThanOrEqualToThreshold'
)
Instance Metadata Service (IMDSv2):
# Use IMDSv2 (more secure than IMDSv1)
import requests
# Get token
token = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=2
).text
# Get metadata with token
metadata = requests.get(
'http://169.254.169.254/latest/meta-data/instance-id',
headers={'X-aws-ec2-metadata-token': token},
timeout=2
).text
🔍 Interviewer Notes: Testing resilience and security practices.
Q104: How do you use EC2 with GuardDuty?
Technical Answer: GuardDuty detects threats (unauthorized access, crypto mining) targeting EC2 instances by analyzing VPC Flow Logs, DNS logs, and CloudTrail events. Enable GuardDuty to monitor EC2 instances without agents.
Code/Config Example:
import boto3
guardduty = boto3.client('guardduty')
# Enable GuardDuty
detector = guardduty.create_detector(
Enable=True,
FindingPublishingFrequency='SIX_HOURS'
)
# Get findings for EC2
findings = guardduty.list_findings(
DetectorId=detector['DetectorId'],
FilterCriteria={
'FilterCriteria': [{
'Criterion': {
'resource.resourceType': {'Eq': ['EC2Instance']}
}
}]
)
🔍 Interviewer Notes: Testing threat detection for EC2.
❌ Common Mistakes:
- Not enabling GuardDuty in all regions
- Ignoring GuardDuty findings
- Not configuring SNS notifications for findings
Q105: How do you use EC2 with Amazon Inspector?
Technical Answer: Amazon Inspector assesses EC2 instances for vulnerabilities (CVEs) and network reachability issues. Install the Inspector agent on EC2 instances to enable continuous scanning.
Code/Config Example:
import boto3
inspector = boto3.client('inspector')
# Create assessment target for EC2 instances
target = inspector.create_assessment_target(
AssessmentTargetName='ec2-instances',
ResourceGroupArn='arn:aws:inspector:us-east-1:123456789:resourcegroup/ec2-instances'
)
# Start assessment run
inspector.start_assessment_run(
AssessmentTemplateArn='arn:aws:inspector:...:template/ec2-scan',
AssessmentRunName='weekly-scan'
)
🔍 Interviewer Notes: Testing vulnerability management for EC2.
❌ Common Mistakes:
- Not installing Inspector agent
- Disabling vulnerability scanning
- Not remediating critical CVEs
Q106: How do you configure EC2 Patch Manager for automated patching?
Technical Answer: Patch Manager automates OS and application patching for EC2 instances using patch baselines and maintenance windows. Define approval rules for patches and schedule maintenance windows for patching.
Code/Config Example:
import boto3
ssm = boto3.client('ssm')
# Create patch baseline
baseline = ssm.create_patch_baseline(
Name='ec2-linux-baseline',
OperatingSystem='AMAZON_LINUX_2',
ApprovalRules={
'PatchRules': [{
'PatchFilterGroup': {
'PatchFilters': [{'Key': 'CLASSIFICATION', 'Values': ['Security']}]
},
'ApproveAfterDays': 7,
'EnableNonSecurity': False
}]
}
)
# Register baseline with patch group
ssm.register_patch_baseline_for_patch_group(
BaselineId=baseline['BaselineId'],
PatchGroup='ec2-web-servers'
)
🔍 Interviewer Notes: Testing automated patch management.
❌ Common Mistakes:
- Not testing patches before deployment
- Patching during peak hours
- Not setting approval rules
Q107: How do you use EC2 with AWS Security Hub?
Technical Answer: Security Hub aggregates security findings (GuardDuty, Inspector, Config) for EC2 instances into a single dashboard. Enable Security Hub standards like CIS AWS Foundations Benchmark for EC2 compliance.
Code/Config Example:
import boto3
securityhub = boto3.client('securityhub')
# Enable Security Hub
securityhub.enable_security_hub()
# Enable CIS standard
securityhub.batch_enable_standards(
StandardsSubscriptionRequests=[{
'StandardsArn': 'arn:aws:securityhub:us-east-1:123456789:standards/cis-aws-foundations-benchmark/v/1.2.0'
}]
)
🔍 Interviewer Notes: Testing security compliance aggregation.
❌ Common Mistakes:
- Not enabling Security Hub in all regions
- Ignoring compliance findings
- Not customizing standards
Q108: What are EC2 security best practices for public instances?
Technical Answer: Public EC2 instances should use Security Groups to restrict inbound access, disable SSH password authentication, use SSM instead of SSH, and enable GuardDuty/Inspector for threat detection.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Security group for public instance (restrict SSH to bastion)
ec2.authorize_security_group_ingress(
GroupId='sg-public-ec2',
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'UserIdGroupPairs': [{'GroupId': 'sg-bastion'}]
}]
)
🔍 Interviewer Notes: Testing public instance security.
❌ Common Mistakes:
- Opening SSH to 0.0.0.0/0
- Using password authentication for SSH
- Not updating OS regularly
Q109: How do you use EC2 with AWS Config?
Technical Answer: AWS Config monitors EC2 instance configuration changes (instance type, security groups, tags) and evaluates compliance against rules. Use Config rules like "ec2-instance-no-public-ip" for compliance.
Code/Config Example:
import boto3
config = boto3.client('config')
# Create Config rule for EC2
config.put_config_rule(
ConfigRule={
'ConfigRuleName': 'ec2-no-public-ip',
'Description': 'EC2 instances should not have public IPs',
'Source': {
'SourceIdentifier': 'EC2_INSTANCE_NO_PUBLIC_IP',
'Owner': 'AWS'
}
}
)
🔍 Interviewer Notes: Testing configuration compliance monitoring.
❌ Common Mistakes:
- Not enabling Config in all regions
- Not setting up remediation actions
- Ignoring non-compliant resources
Q110: What are EC2 security groups best practices?
Technical Answer: Follow least privilege by only allowing required ports, use security group references instead of CIDR blocks, limit rules to 60 inbound/60 outbound, and audit security groups regularly.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Good: Reference security group instead of CIDR
ec2.authorize_security_group_ingress(
GroupId='sg-web',
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 3306,
'ToPort': 3306,
'UserIdGroupPairs': [{'GroupId': 'sg-db'}] # Allow from DB SG only
}]
)
🔍 Interviewer Notes: Testing security group configuration best practices.
❌ Common Mistakes:
- Using 0.0.0.0/0 for all rules
- Referencing self instead of specific SGs
- Too many rules (exceeding limits)
Q111: How do you use EC2 with VPC Flow Logs?
Technical Answer: VPC Flow Logs capture network traffic to/from EC2 instances, sent to CloudWatch Logs or S3. Use for troubleshooting, security analysis, and compliance auditing.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create Flow Log for VPC
ec2.create_flow_logs(
ResourceIds=['vpc-123456'],
ResourceType='VPC',
TrafficType='ALL',
LogDestinationType='cloud-watch-logs',
LogGroupName='/aws/vpc/flow-logs'
)
🔍 Interviewer Notes: Testing network traffic monitoring.
❌ Common Mistakes:
- Not enabling Flow Logs for all VPCs
- Sending logs to S3 without lifecycle policies
- Not analyzing logs for anomalies
Q112: What is EC2 instance metadata security?
Technical Answer: EC2 instance metadata (IMDS) provides instance details; IMDSv2 requires session tokens to prevent SSRF attacks. Enforce IMDSv2 and disable IMDSv1 where possible.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enforce IMDSv2 on new instances
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
MetadataOptions={
'HttpTokens': 'required', # IMDSv2 only
'HttpEndpoint': 'enabled',
'HttpPutResponseHopLimit': 2
}
)
🔍 Interviewer Notes: Testing metadata service security.
❌ Common Mistakes:
- Using IMDSv1 (vulnerable to SSRF)
- Not enforcing IMDSv2
- Setting hop limit too high
Q113: How do you use EC2 with AWS Firewall Manager?
Technical Answer: Firewall Manager centrally configures WAF, Shield, and security group rules across EC2 instances in multiple accounts. Use to enforce consistent security policies across organizations.
Code/Config Example:
import boto3
fms = boto3.client('fms')
# Create security group policy
fms.put_policy(
Policy={
'PolicyName': 'ec2-sg-policy',
'SecurityServicePolicyData': {
'Type': 'SECURITY_GROUPS_COMMON',
'ManagedServiceData': json.dumps({
'type': 'SECURITY_GROUPS_COMMON',
'securityGroups': [{'id': 'sg-123456'}]
})
},
'ResourceTags': [{'Key': 'Environment', 'Value': 'production'}]
}
)
🔍 Interviewer Notes: Testing centralized security policy management.
❌ Common Mistakes:
- Not scoping policies to specific tags
- Overly restrictive policies
- Not testing policies before enforcement
Q114: What are EC2 DDoS protection best practices?
Technical Answer: Protect EC2 instances from DDoS using Shield Standard (default), Shield Advanced for enhanced protection, and WAF for Layer 7 protection. Use ELB to distribute traffic and hide instance IPs.
Code/Config Example:
import boto3
wafv2 = boto3.client('wafv2')
# Create WAF rule to block bad IPs
wafv2.create_ip_set(
Name='blocked-ips',
Scope='REGIONAL',
IPAddressVersion='IPV4',
Addresses=['198.51.100.0/24']
)
🔍 Interviewer Notes: Testing DDoS protection strategies.
❌ Common Mistakes:
- Exposing EC2 instances directly to internet
- Not using Shield Advanced for critical workloads
- Not configuring WAF rules
Q115: How do you use EC2 with AWS WAF?
Technical Answer: WAF filters malicious HTTP/HTTPS traffic to EC2 instances behind ALB. Create WAF rules to block SQL injection, XSS, and bad IPs.
Code/Config Example:
import boto3
wafv2 = boto3.client('wafv2')
# Create WAF web ACL
wafv2.create_web_acl(
Name='ec2-web-acl',
Scope='REGIONAL',
DefaultAction={'Allow': {}},
Rules=[{
'Name': 'block-sql-injection',
'Priority': 1,
'Statement': {
'ManagedRuleGroupStatement': {
'VendorName': 'AWS',
'Name': 'AWSManagedRulesSQLiRuleSet'
}
},
'Action': {'Block': {}}
}]
)
🔍 Interviewer Notes: Testing Layer 7 protection for EC2 web workloads.
❌ Common Mistakes:
- Not associating WAF with ALB
- Overly restrictive rules
- Not monitoring WAF metrics
Q116: What are EC2 encryption best practices?
Technical Answer: Encrypt EBS volumes, snapshots, and S3 buckets used by EC2. Use customer managed KMS keys for control, enable EBS encryption by default, and encrypt AMI backups.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enable EBS encryption by default
ec2.enable_ebs_encryption_by_default()
# Encrypt snapshot
snapshot = ec2.create_snapshot(VolumeId='vol-123')
ec2.copy_snapshot(
SourceSnapshotId=snapshot['SnapshotId'],
SourceRegion='us-east-1',
Encrypted=True
)
🔍 Interviewer Notes: Testing data encryption best practices.
❌ Common Mistakes:
- Not encrypting EBS volumes
- Using default AWS managed keys
- Not encrypting cross-region snapshots
Q117: How do you use EC2 with AWS KMS?
Technical Answer: KMS manages encryption keys for EC2 EBS volumes, S3, and Secrets Manager. EC2 instances with IAM roles can retrieve KMS keys via IMDS to encrypt/decrypt data.
Code/Config Example:
import boto3
kms = boto3.client('kms')
# Create customer managed key for EC2
key = kms.create_key(
Description='EC2 EBS encryption key',
KeyUsage='ENCRYPT_DECRYPT'
)
# Grant EC2 role access to key
kms.create_grant(
KeyId=key['KeyMetadata']['KeyId'],
GranteePrincipal='arn:aws:iam::123456789:role/ec2-role',
Operations=['Encrypt', 'Decrypt']
)
🔍 Interviewer Notes: Testing encryption key management.
❌ Common Mistakes:
- Not rotating KMS keys
- Overly permissive key policies
- Using AWS managed keys for compliance
Q118: What are EC2 IAM role security best practices?
Technical Answer: Follow least privilege by granting only required permissions, use managed policies, rotate roles regularly, and avoid attaching AdministratorAccess to EC2 instances.
Code/Config Example:
import boto3
iam = boto3.client('iam')
# Attach least privilege policy to EC2 role
iam.attach_role_policy(
RoleName='ec2-s3-read',
PolicyArn='arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
)
🔍 Interviewer Notes: Testing IAM role security.
❌ Common Mistakes:
- Using AdministratorAccess for EC2 roles
- Inline policies instead of managed
- Not auditing role permissions
Q119: How do you audit EC2 API calls with CloudTrail?
Technical Answer: CloudTrail logs all EC2 API calls (run-instances, terminate-instances) to S3 for auditing. Enable CloudTrail in all regions to capture EC2 activity.
Code/Config Example:
import boto3
cloudtrail = boto3.client('cloudtrail')
# Create trail for EC2 API calls
cloudtrail.create_trail(
Name='ec2-api-trail',
S3BucketName='cloudtrail-logs-bucket',
IsMultiRegionTrail=True
)
# Start logging
cloudtrail.start_logging(Name='ec2-api-trail')
🔍 Interviewer Notes: Testing API call auditing.
❌ Common Mistakes:
- Not enabling CloudTrail in all regions
- Not encrypting CloudTrail logs
- Not setting up alerts for sensitive API calls
Q120: What are EC2 compliance best practices?
Technical Answer: Meet compliance standards (GDPR, HIPAA, PCI-DSS) by encrypting data, enabling logging, using GuardDuty/Inspector, and documenting security controls for EC2 workloads.
Code/Config Example:
import boto3
# Enable HIPAA compliance controls
securityhub = boto3.client('securityhub')
securityhub.batch_enable_standards(
StandardsSubscriptionRequests=[{
'StandardsArn': 'arn:aws:securityhub:us-east-1:123456789:standards/pci-dss/v/3.2.1'
}]
)
🔍 Interviewer Notes: Testing compliance adherence.
❌ Common Mistakes:
- Not enabling compliance standards
- Missing encryption for sensitive data
- Not documenting security controls
Q121: How do you optimize EC2 costs with Reserved Instances?
Technical Answer: Reserved Instances (RIs) provide 30-75% savings over On-Demand for predictable, steady-state workloads with 1-3 year commitments. Choose Convertible RIs for flexibility or Standard for maximum savings.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Purchase Convertible RI for flexibility
offerings = ec2.describe_reserved_instances_offerings(
InstanceType='m5.large',
OfferingClass='Convertible',
ProductDescription='Linux/UNIX'
)
ec2.purchase_reserved_instances_offering(
ReservedInstancesOfferingId=offerings['ReservedInstancesOfferings'][0]['ReservedInstancesOfferingId'],
InstanceCount=10
)
🔍 Interviewer Notes: Testing long-term cost commitment strategies.
❌ Common Mistakes:
- Buying RIs for variable workloads
- Not using Compute Optimizer to size RIs
- Forgetting to regionalize RIs for flexibility
Q122: What are EC2 Savings Plans vs Reserved Instances?
Technical Answer: Savings Plans offer 30-72% savings with flexible usage across instance families, regions, and OS, while RIs are tied to specific instance families and provide higher discounts for predictable workloads.
Code/Config Example:
# Savings Plans: Flexible compute spend commitment
# aws savingsplans create-savings-plan --offering-id "sp-123" --commitment "20.0" --upfront-payment "1000.0"
# RIs: Tied to specific instance family
ec2.purchase_reserved_instances_offering(
ReservedInstancesOfferingId='offering-123',
InstanceCount=5
)
🔍 Interviewer Notes: Testing modern cost optimization approach.
❌ Common Mistakes:
- Using RIs when workload flexibility is needed
- Over-committing Savings Plans hourly spend
- Not combining both for maximum savings
Q123: How do you use Spot Instances for cost optimization?
Technical Answer: Spot Instances provide up to 90% savings over On-Demand for fault-tolerant workloads. Use capacity-optimized allocation to reduce interruption probability and mix with On-Demand for critical components.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
InstanceMarketOptions={
'MarketType': 'spot',
'SpotOptions': {'AllocationStrategy': 'capacity-optimized'}
}
)
🔍 Interviewer Notes: Testing fault-tolerant cost optimization.
❌ Common Mistakes:
- Using Spot for stateful workloads without checkpointing
- Not diversifying instance types in Spot requests
- Using lowest-price instead of capacity-optimized
Q124: What is EC2 right-sizing and how do you implement it?
Technical Answer: Right-sizing matches instance size to actual workload requirements using CloudWatch metrics or Compute Optimizer. Downsizing over-provisioned instances can reduce costs by 30-50%.
Code/Config Example:
import boto3
compute_optimizer = boto3.client('compute-optimizer')
recommendations = compute_optimizer.get_ec2_instance_recommendations(
InstanceArns=['arn:aws:ec2:us-east-1:123456789:instance/i-123']
)
for rec in recommendations['instanceRecommendations']:
print(f"Recommended: {rec['recommendationOptions'][0]['instanceType']}")
🔍 Interviewer Notes: Testing workload optimization.
❌ Common Mistakes:
- Not monitoring CPU/memory utilization first
- Downsizing too aggressively
- Ignoring application performance impact
Q125: How do you use Compute Optimizer for EC2 cost savings?
Technical Answer: Compute Optimizer analyzes EC2 instance utilization and recommends optimal instance types/sizes. Enable for all instances and implement recommendations to reduce costs and improve performance.
Code/Config Example:
import boto3
compute_optimizer = boto3.client('compute-optimizer')
# Enable Compute Optimizer
compute_optimizer.update_ec2_auto_scaling_group_recommendation_preferences(
AutoScalingGroupArns=['arn:aws:autoscaling:us-east-1:123456789:autoScalingGroup:web-asg'],
UtilizationPreferences=[{'MetricName': 'CPU', 'GlobalDefault': True}]
)
🔍 Interviewer Notes: Testing automated cost optimization.
❌ Common Mistakes:
- Not enabling Compute Optimizer in all regions
- Ignoring recommendations
- Not testing recommended instances first
Q126: What are EC2 cost allocation tags best practices?
Technical Answer: Use cost allocation tags (Environment, Application, Owner) to track EC2 costs by team/project. Enable tag activation in Billing Console and enforce tagging via IAM policies.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [
{'Key': 'Environment', 'Value': 'production'},
{'Key': 'Application', 'Value': 'web-server'},
{'Key': 'Owner', 'Value': 'team-a'}
]
}]
)
🔍 Interviewer Notes: Testing cost attribution.
❌ Common Mistakes:
- Not activating tags in Billing Console
- Inconsistent tagging across instances
- Missing tags on EC2 resources
Q127: How do you monitor EC2 costs with Cost Explorer?
Technical Answer: Cost Explorer analyzes EC2 spend by service, region, instance type, and tags. Create daily/monthly reports and set budget alerts for EC2 costs.
Code/Config Example:
import boto3
ce = boto3.client('ce')
# Get EC2 cost by service
costs = ce.get_cost_and_usage(
TimePeriod={'Start': '2024-04-01', 'End': '2024-05-01'},
Granularity='MONTHLY',
Metrics=['BlendedCost'],
GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}]
)
🔍 Interviewer Notes: Testing cost monitoring.
❌ Common Mistakes:
- Not filtering by EC2-specific costs
- Missing budget alerts
- Not analyzing cost trends
Q128: What is EC2 Spot Fleet cost optimization?
Technical Answer: Spot Fleet mixes Spot and On-Demand instances across multiple types to maintain capacity at lowest cost. Use capacity-optimized allocation to minimize interruptions while maximizing savings.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.request_spot_fleet(
SpotFleetRequestConfig={
'AllocationStrategy': 'capacityOptimized',
'TargetCapacity': 20,
'OnDemandTargetCapacity': 4,
'LaunchTemplateConfigs': [{
'Overrides': [
{'InstanceType': 'm5.large'},
{'InstanceType': 'm5a.large'}
]
}]
}
)
🔍 Interviewer Notes: Testing advanced Spot cost optimization.
❌ Common Mistakes:
- Not mixing On-Demand with Spot
- Using single instance type in Spot Fleet
- Not setting max price
Q129: How do you use EC2 Auto Scaling for cost optimization?
Technical Answer: Auto Scaling matches capacity to demand, scaling out during peaks and in during valleys. Use target tracking scaling to maintain optimal utilization and minimize idle capacity.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.put_scaling_policy(
AutoScalingGroupName='web-asg',
PolicyName='cpu-target',
PolicyType='TargetTrackingScaling',
TargetTrackingConfiguration={
'PredefinedMetricSpecification': {'PredefinedMetricType': 'ASGAverageCPUUtilization'},
'TargetValue': 50.0
}
)
🔍 Interviewer Notes: Testing elastic cost optimization.
❌ Common Mistakes:
- Over-provisioning MinSize
- Not setting scale-in cooldown
- Using static instance counts
Q130: What are EC2 Graviton cost benefits?
Technical Answer: Graviton instances (M7g, C7g, R7g) provide up to 40% better price/performance over x86 instances for compatible workloads. Ideal for web servers, caches, and microservices.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0', # ARM AMI
InstanceType='m7g.medium', # Graviton 3
MinCount=1,
MaxCount=1
)
🔍 Interviewer Notes: Testing ARM-based cost optimization.
❌ Common Mistakes:
- Using x86 AMIs with Graviton
- Not testing application compatibility
- Ignoring Graviton for compatible workloads
Q131: How do you use EC2 Spot blocks for batch workloads?
Technical Answer: Spot blocks reserve Spot Instances for fixed durations (1-6 hours) without interruption. Ideal for batch processing, CI/CD jobs, and data processing tasks.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
InstanceMarketOptions={
'MarketType': 'spot',
'SpotOptions': {
'SpotInstanceType': 'one-time',
'BlockDurationMinutes': 240 # 4 hours
}
}
)
🔍 Interviewer Notes: Testing batch workload cost optimization.
❌ Common Mistakes:
- Using Spot blocks for long-running workloads
- Not handling block expiration
- Overpaying for short blocks
Q132: What is EC2 capacity reservation cost impact?
Technical Answer: Capacity Reservations guarantee capacity at no additional cost (unless combined with RIs/Savings Plans). They have no discounts, so use only when capacity guarantee is required.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.create_capacity_reservation(
InstanceType='p4d.24xlarge',
InstancePlatform='Linux/UNIX',
AvailabilityZone='us-east-1a',
InstanceCount=2
)
🔍 Interviewer Notes: Testing capacity planning costs.
❌ Common Mistakes:
- Using Capacity Reservations unnecessarily
- Not combining with RIs/Savings Plans
- Forgetting to release unused reservations
Q133: How do you avoid EC2 unnecessary costs?
Technical Answer: Eliminate idle instances, orphaned EBS volumes/snapshots, unused Elastic IPs, and over-provisioned instance sizes. Use AWS Cost Anomaly Detection to spot unexpected spend.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Find stopped instances over 7 days
# Check instance state and launch time
# Terminate unused stopped instances
🔍 Interviewer Notes: Testing cost waste elimination.
❌ Common Mistakes:
- Leaving stopped instances running
- Not cleaning up old snapshots
- Ignoring cost anomaly alerts
Q134: What are EC2 storage cost optimization tips?
Technical Answer: Use gp3 instead of gp2 (lower cost, better performance), delete unused snapshots, resize EBS volumes to minimum required, and use instance store for temporary data.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Modify volume to gp3
ec2.modify_volume(
VolumeId='vol-1234567890abcdef0',
VolumeType='gp3',
Size=50,
Iops=3000
)
🔍 Interviewer Notes: Testing storage cost optimization.
❌ Common Mistakes:
- Using gp2 instead of gp3
- Over-provisioning EBS size
- Not deleting old snapshots
Q135: How do you use EC2 scheduled scaling for cost savings?
Technical Answer: Scheduled scaling reduces capacity during off-peak hours (nights, weekends) for predictable workloads. Combine with Auto Scaling to automatically scale in when demand drops.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.put_scheduled_update_group_action(
AutoScalingGroupName='web-asg',
ScheduledActionName='scale-in-weekends',
Recurrence='0 20 * * FRI', # Friday 8 PM
DesiredCapacity=2
)
🔍 Interviewer Notes: Testing time-based cost optimization.
❌ Common Mistakes:
- Not considering time zones
- Conflicting scheduled actions
- Scaling in too aggressively
Q136: What is EC2 Spot interruption cost impact?
Technical Answer: Spot interruptions can increase costs if workloads need to restart frequently. Use capacity-optimized allocation, checkpoint state, and mix with On-Demand to mitigate interruption costs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Check Spot interruption notice
# Handle checkpointing to avoid rework costs
🔍 Interviewer Notes: Testing Spot risk management.
❌ Common Mistakes:
- Not handling interruptions gracefully
- Using Spot for stateful apps
- Ignoring interruption frequency
Q137: How do you use EC2 mixed instances for cost optimization?
Technical Answer: Mixed Instances Policy launches multiple instance types in Auto Scaling groups, using cheapest available types first. Improves availability and reduces costs by using diverse Spot options.
Code/Config Example:
import boto3
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='mixed-asg',
MixedInstancesPolicy={
'LaunchTemplate': {'LaunchTemplateId': 'lt-123'},
'InstancesDistribution': {
'OnDemandPercentageAboveBaseCapacity': 20,
'SpotAllocationStrategy': 'capacity-optimized'
}
}
)
🔍 Interviewer Notes: Testing flexible instance provisioning.
❌ Common Mistakes:
- Not diversifying instance types enough
- Using same instance family only
- Not testing all instance types
Q138: What are EC2 data transfer cost best practices?
Technical Answer: Minimize cross-AZ data transfer (free in same AZ), use S3 VPC endpoints to avoid NAT costs, and use CloudFront for content delivery to reduce EC2 data transfer.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create S3 VPC endpoint to avoid NAT costs
ec2.create_vpc_endpoint(
VpcId='vpc-123456',
ServiceName='com.amazonaws.us-east-1.s3',
VpcEndpointType='Gateway'
)
🔍 Interviewer Notes: Testing data transfer cost reduction.
❌ Common Mistakes:
- Not using VPC endpoints for S3/DynamoDB
- Cross-AZ traffic without need
- Not using CloudFront for static assets
Q139: How do you use EC2 Graviton for MySQL cost savings?
Technical Answer: Graviton 3 instances (M7g, R7g) provide up to 30% cost savings for MySQL/MariaDB workloads with better performance. Use Amazon Linux 2 ARM or Ubuntu ARM AMIs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0', # ARM AMI
InstanceType='r7g.large', # Memory-optimized Graviton
MinCount=1,
MaxCount=1
)
🔍 Interviewer Notes: Testing database cost optimization.
❌ Common Mistakes:
- Not testing MySQL compatibility with ARM
- Using x86 AMIs
- Ignoring Graviton for RDS Custom
Q140: What is EC2 cost anomaly detection?
Technical Answer: AWS Cost Anomaly Detection uses ML to spot unusual EC2 spend patterns. Configure alerts for EC2 service to catch unexpected cost spikes from unused resources or misconfigurations.
Code/Config Example:
import boto3
ce = boto3.client('ce')
ce.create_anomaly_monitor(
AnomalyMonitor={
'MonitorName': 'ec2-cost-monitor',
'MonitorType': 'DIMENSIONAL',
'DimensionalValue': 'Amazon Elastic Compute Cloud - Compute'
}
)
🔍 Interviewer Notes: Testing proactive cost monitoring.
❌ Common Mistakes:
- Not setting up cost anomaly alerts
- Ignoring anomaly notifications
- Not linking to SNS for alerts
Q141: How do you enable Enhanced Networking for EC2?
Technical Answer: Enhanced Networking uses SR-IOV to provide high throughput, low latency, and low jitter. Supported on most modern instances (C5, M5, R5, etc.) via ENA adapter.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance with ENA (default for supported types)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.large', # Supports ENA
EnaSupport=True
)
🔍 Interviewer Notes: Testing high-performance networking.
❌ Common Mistakes:
- Using instance types without ENA support
- Not installing ENA drivers on custom AMIs
- Disabling ENA accidentally
Q142: What is Elastic Fabric Adapter (EFA) and use cases?
Technical Answer: EFA provides low-latency, high-throughput communication for HPC and ML workloads using OS-bypass technology. Requires cluster placement group and supported instance types (C5n, P4, etc.).
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.24xlarge',
NetworkInterfaces=[{'DeviceIndex': 0, 'InterfaceType': 'efa'}],
Placement={'GroupName': 'hpc-cluster'}
)
🔍 Interviewer Notes: Testing HPC networking.
❌ Common Mistakes:
- Using EFA without cluster placement group
- Not installing EFA drivers
- Using EFA for non-HPC workloads
Q143: How do you configure EFA for HPC workloads?
Technical Answer: Install EFA drivers on the OS, configure MPI (Message Passing Interface) to use EFA, and launch instances in cluster placement group for lowest latency.
Code/Config Example:
# On EC2 instance
sudo yum install -y gcc gcc-c++ make
tar -xf efa-installer.tar.gz
sudo ./efa_installer.sh
# Configure OpenMPI to use EFA
export FI_PROVIDER=efa
mpirun -np 16 ./hpc-app
🔍 Interviewer Notes: Testing HPC configuration.
❌ Common Mistakes:
- Not installing EFA drivers
- Missing MPI configuration
- Not using cluster placement group
Q144: What are EC2 network performance metrics?
Technical Answer: Monitor NetworkIn/NetworkOut (bytes), NetworkPacketsIn/Out, and EFA-specific metrics via CloudWatch. Use these to optimize network configuration.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='NetworkOut',
Dimensions=[{'Name': 'InstanceId', 'Value': 'i-123'}],
Period=300,
Statistics=['Average', 'Maximum']
)
🔍 Interviewer Notes: Testing network observability.
❌ Common Mistakes:
- Not monitoring network metrics
- Missing EFA-specific metrics
- Not setting network alarms
Q145: How do you optimize EC2 network throughput?
Technical Answer: Use instances with higher network bandwidth, enable Enhanced Networking/EFA, use jumbo frames (MTU 9001), and distribute traffic across multiple ENIs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch instance with high network performance
ec2.run_instances(
ImageType='c6in.large', # Up to 100 Gbps
MinCount=1,
MaxCount=1
)
🔍 Interviewer Notes: Testing network performance optimization.
❌ Common Mistakes:
- Using instances with low bandwidth
- Not enabling jumbo frames
- Single ENI for high throughput
Q146: What is EC2 ENA (Elastic Network Adapter)?
Technical Answer: ENA is the default network driver for Enhanced Networking on EC2, supporting up to 100 Gbps throughput. It provides SR-IOV for better performance over traditional virtualized NICs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Check ENA support
response = ec2.describe_instances(InstanceIds=['i-123'])
ena_support = response['Reservations'][0]['Instances'][0]['EnaSupport']
🔍 Interviewer Notes: Testing network driver knowledge.
❌ Common Mistakes:
- Confusing ENA with EFA
- Not checking ENA support
- Disabling ENA on supported instances
Q147: How do you use EC2 with Elastic IPs for FTP?
Technical Answer: Associate Elastic IP to EC2 instance running FTP server for consistent IP. Configure passive FTP ports and update security groups to allow inbound FTP traffic.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.authorize_security_group_ingress(
GroupId='sg-ftp',
IpPermissions=[
{'IpProtocol': 'tcp', 'FromPort': 21, 'ToPort': 21, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
{'IpProtocol': 'tcp', 'FromPort': 50000, 'ToPort': 51000, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
]
)
🔍 Interviewer Notes: Testing static IP for legacy protocols.
❌ Common Mistakes:
- Using EIP for FTP instead of NLB
- Not opening passive FTP ports
- Leaving FTP unencrypted
Q148: What are EC2 network interface attachment limits?
Technical Answer:
Each instance type has a maximum number of ENIs and private IPs per ENI. Check describe_instance_types for limits and use larger instances for network-heavy workloads.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_instance_types(InstanceTypes=['m5.large'])
max_enis = response['InstanceTypes'][0]['NetworkInfo']['MaximumNetworkInterfaces']
🔍 Interviewer Notes: Testing instance network limits.
❌ Common Mistakes:
- Exceeding ENI limits
- Not checking limits before launch
- Using small instances for network-heavy workloads
Q149: How do you configure EC2 jumbo frames (MTU)?
Technical Answer: Jumbo frames (MTU 9001) increase network throughput by sending larger packets. Enable on EC2 instance OS and ensure VPC/ENI supports it.
Code/Config Example:
# On Amazon Linux 2
sudo ip link set dev eth0 mtu 9001
# Persist across reboots
echo "MTU=9001" | sudo tee -a /etc/sysconfig/network-scripts/ifcfg-eth0
🔍 Interviewer Notes: Testing network optimization.
❌ Common Mistakes:
- Not enabling on OS side
- Using jumbo frames with non-supported instances
- Not testing for packet fragmentation
Q150: What is EC2 IPv6 egress-only internet gateway?
Technical Answer: Egress-only internet gateway allows IPv6 instances to access internet but blocks inbound traffic. Use for IPv6 instances that need outbound-only internet access.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.create_egress_only_internet_gateway(
VpcId='vpc-123456'
)
# Add route to route table: destination ::/0, target egress-only-igw
🔍 Interviewer Notes: Testing IPv6 outbound access.
❌ Common Mistakes:
- Using regular IGW for IPv6 egress
- Not configuring routes
- Allowing inbound IPv6 traffic accidentally
Q151: How do you use EC2 with transit gateway?
Technical Answer: Transit Gateway connects multiple VPCs and on-premises networks via a central hub. Attach EC2 VPCs to Transit Gateway for simplified network architecture.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
tgw = ec2.create_transit_gateway(Description='Central TGW')
ec2.create_transit_gateway_vpc_attachment(
TransitGatewayId=tgw['TransitGateway']['TransitGatewayId'],
VpcId='vpc-123456',
SubnetIds=['subnet-123']
)
🔍 Interviewer Notes: Testing global network connectivity.
❌ Common Mistakes:
- Not configuring TGW routing
- Missing TGW attachments
- Not enabling DNS support
Q152: What are EC2 network costs best practices?
Technical Answer: Minimize cross-AZ data transfer, use VPC endpoints for S3/DynamoDB, use CloudFront for content delivery, and avoid NAT Gateway for high-volume traffic.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create S3 VPC endpoint to avoid NAT costs
ec2.create_vpc_endpoint(
VpcId='vpc-123456',
ServiceName='com.amazonaws.us-east-1.s3',
VpcEndpointType='Gateway'
)
🔍 Interviewer Notes: Testing network cost optimization.
❌ Common Mistakes:
- High cross-AZ data transfer
- Not using VPC endpoints
- Using NAT Gateway for S3 access
Q153: How do you configure EC2 for multicast?
Technical Answer: EC2 does not natively support multicast; use Transit Gateway multicast or third-party appliances. Enable multicast support on Transit Gateway and register EC2 instances as group members.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.enable_transit_gateway_route_table_propagation(
TransitGatewayRouteTableId='tgw-rtb-123',
TransitGatewayAttachmentId='tgw-attach-123'
)
🔍 Interviewer Notes: Testing multicast networking.
❌ Common Mistakes:
- Expecting native multicast support
- Not using Transit Gateway
- Misconfiguring multicast groups
Q154: What is EC2 network ACL best practices?
Technical Answer: Use NACLs as a secondary security layer (in addition to security groups) for broad subnet-level rules. Follow stateless rules (explicit allow/deny for inbound/outbound).
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.create_network_acl_entry(
NetworkAclId='acl-123456',
RuleNumber=100,
Protocol='6', # TCP
RuleAction='allow',
Egress=False,
CidrBlock='10.0.0.0/16',
PortRange={'From': 80, 'To': 80}
)
🔍 Interviewer Notes: Testing subnet-level security.
❌ Common Mistakes:
- Using NACLs as primary security layer
- Forgetting stateless nature (need inbound + outbound rules)
- Overly restrictive NACLs blocking legitimate traffic
Q155: How do you use EC2 with NAT instances vs NAT Gateway?
Technical Answer: NAT Gateway is managed, highly available, and supports up to 45 Gbps. NAT instances are self-managed, lower cost for low throughput, but require manual HA configuration.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create managed NAT Gateway (preferred)
ec2.create_nat_gateway(
SubnetId='subnet-public',
AllocationId='eipalloc-123456'
)
🔍 Interviewer Notes: Testing NAT options.
❌ Common Mistakes:
- Using NAT instances for production
- NAT Gateway in private subnet
- Not using multiple AZs for HA
Q156: What are EC2 DNS resolution options?
Technical Answer: Enable DNS hostnames/DNS resolution on VPC for EC2 instances to resolve AWS services. Use Route 53 private hosted zones for custom internal DNS.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
ec2.modify_vpc_tenancy(
VpcId='vpc-123456',
EnableDnsSupport=True,
EnableDnsHostnames=True
)
🔍 Interviewer Notes: Testing DNS configuration.
❌ Common Mistakes:
- Disabling DNS support on VPC
- Not using Route 53 for internal DNS
- Hardcoding IPs instead of DNS names
Q157: How do you configure EC2 for VPN access?
Technical Answer: Deploy Virtual Private Gateway (VGW) on VPC, create VPN connection, and configure customer gateway on on-premises side. EC2 instances access on-premises resources via VPN.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
vgw = ec2.create_virtual_private_gateway(Type='ipsec.1')
ec2.attach_virtual_private_gateway(
VpcId='vpc-123456',
VirtualPrivateGatewayId=vgw['VirtualPrivateGateway']['VirtualPrivateGatewayId']
)
🔍 Interviewer Notes: Testing hybrid networking.
❌ Common Mistakes:
- Not configuring customer gateway
- Missing route table entries
- Using wrong VPN type
Q158: What is EC2 VPC peering advanced configuration?
Technical Answer: VPC peering requires non-overlapping CIDRs, route table entries in both VPCs, and security group rules to allow cross-VPC traffic. No transitive peering.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Update route table for peering
ec2.create_route(
RouteTableId='rtb-123456',
DestinationCidrBlock='10.1.0.0/16',
VpcPeeringConnectionId='pcx-123456'
)
🔍 Interviewer Notes: Testing VPC networking.
❌ Common Mistakes:
- Overlapping CIDR blocks
- Missing route table entries
- Expecting transitive peering
Q159: How do you use EC2 with Direct Connect?
Technical Answer: Direct Connect provides dedicated network connection from on-premises to AWS. Use with Virtual Private Gateway to provide EC2 instances private access to on-premises resources.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Associate Direct Connect gateway with VGW
ec2.allocate_address(Domain='vpc') # Not directly, use DX console/CLI
🔍 Interviewer Notes: Testing dedicated network connectivity.
❌ Common Mistakes:
- Not configuring BGP routes
- Missing VGW attachment
- Not using DX for high-bandwidth needs
Q160: What are EC2 network troubleshooting steps?
Technical Answer: Check security groups, NACLs, route tables, VPC endpoints, and network ACLs. Use VPC Reachability Analyzer and EC2 Instance Connect for testing.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Check network ACLs for subnet
response = ec2.describe_network_acls(
Filters=[{'Name': 'association.subnet-id', 'Values': ['subnet-123']}]
)
🔍 Interviewer Notes: Testing network debugging skills.
❌ Common Mistakes:
- Not checking all network layers
- Ignoring NACL rules
- Not using Reachability Analyzer
Q161: How do you use EC2 instance store vs EBS?
Technical Answer: Instance store is ephemeral, high-performance storage physically attached to host, lost on stop/terminate. EBS is persistent, network-attached storage, surviving instance stops/termination.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch with instance store (C6id: 'd' = instance store)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6id.4xlarge', # Instance store type
BlockDeviceMappings=[{
'DeviceName': '/dev/sdb',
'VirtualName': 'ephemeral0'
}]
)
# Launch with EBS (persistent)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large',
BlockDeviceMappings=[{
'DeviceName': '/dev/xvda',
'Ebs': {'VolumeType': 'gp3', 'Size': 100}
}]
)
🔍 Interviewer Notes: Testing storage selection.
❌ Common Mistakes:
- Storing persistent data on instance store
- Not backing up instance store data
- Using EBS for high-IOPS temp data
Q162: What are EC2 EBS optimized instances?
Technical Answer: EBS-optimized instances provide dedicated network bandwidth for EBS I/O, preventing contention with network traffic. Enabled by default on most modern instances (M5, C5, R5, etc.).
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enable EBS optimization (default on supported types)
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='m5.large', # EBS optimized by default
EbsOptimized=True
)
🔍 Interviewer Notes: Testing storage performance optimization.
❌ Common Mistakes:
- Disabling EBS optimization accidentally
- Using non-optimized instance types for EBS-heavy workloads
- Not checking EBS optimization support
Q163: How do you configure EBS volume stripping?
Technical Answer: Stripe multiple EBS volumes (RAID 0) to increase throughput and IOPS beyond single-volume limits. Use OS-level RAID for combining multiple gp3/io2 volumes.
Code/Config Example:
# On Linux instance
sudo mdadm --create /dev/md0 --level=0 --raid-devices=4 /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1
sudo mkfs.xfs /dev/md0
sudo mkdir -p /data
sudo mount /dev/md0 /data
🔍 Interviewer Notes: Testing advanced storage configuration.
❌ Common Mistakes:
- Not matching volume types in RAID array
- Forgetting to update /etc/fstab for persistence
- Using RAID for persistent storage (EBS already redundant)
Q164: What is EC2 EBS encryption at rest?
Technical Answer: EBS encryption uses AES-256 to encrypt all data on EBS volumes, snapshots, and data in transit between EC2 and EBS. Enable via KMS keys, default or customer-managed.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create encrypted EBS volume
ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='io2',
Encrypted=True,
KmsKeyId='arn:aws:kms:us-east-1:123456789:key/1234abcd'
)
🔍 Interviewer Notes: Testing data encryption compliance.
❌ Common Mistakes:
- Not encrypting boot volumes
- Using default KMS key for compliance needs
- Forgetting snapshots of encrypted volumes are encrypted
Q165: How do you monitor EBS performance metrics?
Technical Answer: Monitor EBS metrics: VolumeReadBytes/WriteBytes, VolumeReadOps/WriteOps, VolumeQueueLength, BurstBalance (gp2/gp3) via CloudWatch.
Code/Config Example:
import boto3
cloudwatch = boto3.client('cloudwatch')
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EBS',
MetricName='VolumeReadOps',
Dimensions=[{'Name': 'VolumeId', 'Value': 'vol-1234567890abcdef0'}],
Period=300,
Statistics=['Average', 'Maximum']
)
🔍 Interviewer Notes: Testing storage observability.
❌ Common Mistakes:
- Not monitoring burst balance (gp2/gp3)
- Missing IOPS/throughput metrics
- Not setting EBS performance alarms
Q166: What are EC2 instance store RAID configurations?
Technical Answer: Instance store volumes can be striped (RAID 0) for higher throughput, or mirrored (RAID 1) for redundancy (though instance store is already ephemeral). Ideal for temporary high-performance storage.
Code/Config Example:
# RAID 0 for max performance
sudo mdadm --create /dev/md0 --level=0 --raid-devices=2 /dev/nvme1n1 /dev/nvme2n1
sudo mkfs.xfs /dev/md0
🔍 Interviewer Notes: Testing temporary storage optimization.
❌ Common Mistakes:
- Using RAID 1 for ephemeral storage (waste of space)
- Not considering instance store loss on stop
- Forgetting RAID configuration on reboot
Q167: How do you optimize EBS for databases?
Technical Answer: Use io2 Block Express for critical databases (up to 256,000 IOPS, 4,000 MB/s). Provision IOPS/throughput matching database requirements, and use separate volumes for data/logs.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create io2 Block Express volume for database
ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=1000,
VolumeType='io2',
Iops=50000,
Throughput=1000 # MB/s
)
🔍 Interviewer Notes: Testing database storage optimization.
❌ Common Mistakes:
- Using gp3 for high-IOPS databases
- Not separating data and log volumes
- Over-provisioning IOPS
Q168: What is EC2 EBS multi-attach?
Technical Answer: EBS Multi-Attach allows a single io2/io2 Block Express volume to attach to up to 16 EC2 instances in same AZ. Use for shared storage (clusters, HA databases).
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create multi-attach enabled volume
volume = ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='io2',
MultiAttachEnabled=True
)
# Attach to multiple instances
for instance_id in ['i-123', 'i-456']:
ec2.attach_volume(VolumeId=volume['VolumeId'], InstanceId=instance_id, Device='/dev/sdf')
🔍 Interviewer Notes: Testing shared storage configuration.
❌ Common Mistakes:
- Using non-io2 volumes for multi-attach
- Attaching across AZs
- Not using cluster-aware file system
Q169: How do you use EBS snapshots for disaster recovery?
Technical Answer: Copy EBS snapshots to secondary AWS regions for DR. Use snapshot lifecycle policies to automate cross-region copies and retain snapshots per RPO requirements.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Copy snapshot to DR region
ec2.copy_snapshot(
SourceSnapshotId='snap-1234567890abcdef0',
SourceRegion='us-east-1',
DestinationRegion='us-west-2',
Description='DR copy',
Encrypted=True
)
🔍 Interviewer Notes: Testing DR strategies.
❌ Common Mistakes:
- Not encrypting cross-region copies
- Not testing DR restores
- Retaining too many old snapshots
Q170: What are EC2 storage I/O performance best practices?
Technical Answer: Use EBS-optimized instances, provision adequate IOPS/throughput, use RAID 0 for striping, and match file system block size to EBS block size (4KB-16KB).
Code/Config Example:
# Format XFS with 4KB block size (matches EBS)
sudo mkfs.xfs -b size=4096 /dev/xvdf
🔍 Interviewer Notes: Testing I/O optimization.
❌ Common Mistakes:
- Using default file system block size
- Not aligning I/O to EBS block size
- Over-provisioning IOPS
Q171: How do you configure EBS for high throughput?
Technical Answer: Use gp3 (up to 1,000 MB/s) or io2 Block Express (up to 4,000 MB/s). Provision throughput directly on gp3/io2 volumes, or stripe multiple volumes.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# gp3 with provisioned throughput
ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='gp3',
Throughput=1000 # Max 1,000 MB/s
)
🔍 Interviewer Notes: Testing throughput optimization.
❌ Common Mistakes:
- Using gp2 (max 250 MB/s)
- Not provisioning throughput on gp3
- Expecting single-volume >1,000 MB/s (use io2)
Q172: What is EC2 instance store lifecycle?
Technical Answer: Instance store data persists during instance stop (if supported) but is lost on terminate or host failure. Data is ephemeral, so use for cache, buffers, or temporary processing only.
Code/Config Example:
# Check if instance store is present
lsblk | grep nvme
# Instance store data lost on terminate!
🔍 Interviewer Notes: Testing ephemeral storage lifecycle.
❌ Common Mistakes:
- Storing persistent data on instance store
- Not backing up data before stop/terminate
- Expecting data persistence across hosts
Q173: How do you use EBS volumes across AZs?
Technical Answer: EBS volumes are tied to a single AZ. To move across AZs, create a snapshot, then create a new volume in target AZ from the snapshot.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Create snapshot in original AZ
snapshot = ec2.create_snapshot(VolumeId='vol-123', Description='AZ migration')
ec2.wait_until_snapshot_completed(SnapshotIds=[snapshot['SnapshotId']])
# Create volume in new AZ
new_volume = ec2.create_volume(
SnapshotId=snapshot['SnapshotId'],
AvailabilityZone='us-east-1b'
)
🔍 Interviewer Notes: Testing cross-AZ storage migration.
❌ Common Mistakes:
- Trying to attach EBS across AZs directly
- Not encrypting snapshots for cross-AZ copy
- Forgetting to update instance mount points
Q174: What are EC2 EBS snapshot lifecycle policies?
Technical Answer: Use DLM (Data Lifecycle Manager) to automate EBS snapshot creation, retention, and deletion. Set policies for daily snapshots, retain 7-30 days per RPO/RTO needs.
Code/Config Example:
import boto3
dlm = boto3.client('dlm')
dlm.create_lifecycle_policy(
PolicyDetails={
'PolicyType': 'EBS_SNAPSHOT_MANAGEMENT',
'ResourceTypes': ['VOLUME'],
'TargetTags': [{'Key': 'Backup', 'Value': 'Daily'}],
'Schedules': [{
'Name': 'DailySnapshots',
'Frequency': 'DAILY',
'RetainRule': {'Count': 7}
}]
}
)
🔍 Interviewer Notes: Testing automated backup management.
❌ Common Mistakes:
- Not automating snapshot lifecycle
- Retaining too many old snapshots
- Not tagging volumes for DLM
Q175: How do you optimize EBS costs for EC2?
Technical Answer: Right-size EBS volumes, delete unused volumes/snapshots, use gp3 instead of io2 for non-critical workloads, and enable EBS encryption by default.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Delete unused snapshot
ec2.delete_snapshot(SnapshotId='snap-unused123')
# Modify volume to smaller size (after shrinking file system)
ec2.modify_volume(VolumeId='vol-123', Size=50)
🔍 Interviewer Notes: Testing storage cost optimization.
❌ Common Mistakes:
- Over-provisioning EBS size
- Retaining unused snapshots
- Using io2 for low-IOPS workloads
Q176: What is EC2 instance store for caching?
Technical Answer: Instance store provides low-latency, high-IOPS storage ideal for caches (Redis, Memcached) and temporary data. Data is lost on terminate, so use for non-persistent cache only.
Code/Config Example:
# Mount instance store for Redis
sudo mkdir -p /mnt/redis
sudo mount /dev/nvme1n1 /mnt/redis
# Configure Redis to use /mnt/redis for temp data
🔍 Interviewer Notes: Testing cache storage selection.
❌ Common Mistakes:
- Using instance store for persistent cache
- Not configuring cache eviction policies
- Expecting data persistence across restarts
Q177: How do you use EBS with EC2 Auto Scaling?
Technical Answer: Use launch templates to define EBS volume configuration for Auto Scaling groups. For shared data, use EFS or S3 instead of attaching EBS volumes to ASG instances.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Launch template with EBS config
ec2.create_launch_template(
LaunchTemplateName='asg-template',
LaunchTemplateData={
'BlockDeviceMappings': [{
'DeviceName': '/dev/xvda',
'Ebs': {'VolumeType': 'gp3', 'Size': 20, 'Encrypted': True}
}]
}
)
🔍 Interviewer Notes: Testing Auto Scaling storage configuration.
❌ Common Mistakes:
- Attaching static EBS volumes to ASG instances
- Not encrypting EBS in launch templates
- Forgetting to match EBS to instance type
Q178: What are EC2 storage throughput limits?
Technical Answer: EBS throughput limits: gp3 (1,000 MB/s), io2 (4,000 MB/s), instance store (up to 16 GB/s). Check instance type limits for attached storage throughput.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_instance_types(InstanceTypes=['m5.large'])
print(response['InstanceTypes'][0]['EbsInfo']['EbsBandwidthMbps']) # EBS throughput limit
🔍 Interviewer Notes: Testing storage throughput awareness.
❌ Common Mistakes:
- Exceeding instance EBS bandwidth limit
- Not provisioning enough throughput on volume
- Using gp2 for high throughput needs
Q179: How do you configure EBS encryption for backups?
Technical Answer: Enable encryption by default for all EBS volumes, and snapshots inherit encryption from parent volumes. Use customer-managed KMS keys for backup encryption compliance.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# Enable EBS encryption by default
ec2.enable_ebs_encryption_by_default()
# Snapshot of encrypted volume is automatically encrypted
snapshot = ec2.create_snapshot(VolumeId='vol-encrypted-123')
🔍 Interviewer Notes: Testing backup encryption practices.
❌ Common Mistakes:
- Not encrypting backup snapshots
- Using default KMS key for compliance
- Forgetting cross-region encrypted copies
Q180: What is EC2 instance store vs EBS for HPC?
Technical Answer: Instance store provides lowest latency for HPC temporary data; EBS (io2) for persistent HPC datasets. Use EFA with instance store for inter-node communication.
Code/Config Example:
import boto3
ec2 = boto3.client('ec2')
# HPC instance with instance store + EFA
ec2.run_instances(
ImageId='ami-0123456789abcdef0',
InstanceType='c6i.24xlarge', # Instance store + EFA
NetworkInterfaces=[{'InterfaceType': 'efa'}]
)
🔍 Interviewer Notes: Testing HPC storage selection.
❌ Common Mistakes:
- Using EBS for HPC temp data
- Not using EFA for HPC communication
- Mixing storage types incorrectly
3. Advanced Topics
Q181: How do you implement Nitro Enclaves?
Technical Answer: Nitro Enclaves provide isolated compute environments for sensitive data processing.
import boto3
ec2 = boto3.client('ec2')
# Launch with enclave enabled
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='m5.xlarge',
MinCount=1,
MaxCount=1,
EnclaveOptions={'Enabled': True}
)
🔍 Interviewer Notes: Testing advanced security features.
Q182: How do you optimize EC2 costs?
Technical Answer:
Cost Optimization Strategies:
- Use Graviton instances (better price/performance)
- Reserved Instances for predictable workloads
- Spot Instances for fault-tolerant workloads
- Savings Plans for flexible commitments
- Right-sizing with Compute Optimizer
- Auto Scaling to match demand
Reserved Instance Example:
import boto3
ec2 = boto3.client('ec2')
# Purchase reserved capacity
ri = ec2.purchase_reserved_instances_offering(
ReservedInstancesOfferingId='offering-xxx',
InstanceCount=5,
DryRun=False
)
🔍 Interviewer Notes: Testing cost management expertise.
Section 4: Extended Advanced Questions
Q183: What are EC2 placement groups and when to use them?
Technical Answer: Placement groups determine how instances are placed on underlying hardware.
Cluster Placement Group:
import boto3
ec2 = boto3.client('ec2')
# Create cluster placement group (low latency, HPC)
ec2.create_placement_group(
GroupName='hpc-cluster',
Strategy='cluster',
Tags=[{'Key': 'Name', 'Value': 'HPC Cluster'}]
)
# Launch instances in cluster
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='c6i.24xlarge',
MinCount=2,
MaxCount=10,
Placement={'GroupName': 'hpc-cluster'},
EbsOptimized=True,
EnaSupport=True # Enhanced networking
)
Spread Placement Group:
# Spread instances across hardware (isolation)
ec2.create_placement_group(
GroupName='critical-apps',
Strategy='spread'
)
# Limited to 7 instances per AZ
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='m6i.large',
MinCount=1,
MaxCount=7,
Placement={'GroupName': 'critical-apps'}
)
Partition Placement Group:
# Multiple isolated groups (Cassandra, HDFS)
ec2.create_placement_group(
GroupName='distributed-storage',
Strategy='partition',
PartitionCount=3
)
# Each partition isolated from others
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='r6i.2xlarge',
MinCount=3,
MaxCount=9,
Placement={
'GroupName': 'distributed-storage',
'PartitionNumber': 1 # Assign to partition
}
)
| Strategy | Use Case | Limits |
|---|---|---|
| Cluster | HPC, low latency | Same AZ, same hardware |
| Spread | Critical apps, isolation | 7 per AZ, separate hardware |
| Partition | Distributed storage | Multiple groups, rack isolation |
🔍 Interviewer Notes: Testing understanding of instance placement for performance/availability.
❌ Common Mistakes:
- Using cluster when spread needed (different risk tolerance)
- Not considering placement group limits
- Not using with enhanced networking
Q184: What is EC2 hibernation and how does it work?
Technical Answer: Hibernation saves instance state (RAM) to EBS before stopping, allowing fast resume.
How it works:
- On hibernation: RAM contents compressed and saved to root volume
- Instance stopped (not terminated)
- On start: RAM restored from EBS, applications resume
Requirements:
- Nitro-based instances
- Root volume must be EBS, encrypted, large enough for RAM
- Instance RAM <= 16 GB (most instance types)
- Amazon Linux 2, Ubuntu 16.04+, Windows Server 2016+
import boto3
ec2 = boto3.client('ec2')
# Create encrypted AMI for hibernation
response = ec2.create_image(
InstanceId='i-123',
Name='hibernation-ami',
NoReboot=False
)
# Launch with hibernation enabled
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='m5.large',
MinCount=1,
MaxCount=1,
HibernationOptions={'Configured': True},
BlockDeviceMappings=[{
'DeviceName': '/dev/xvda',
'Ebs': {
'VolumeSize': 20, # Must be >= RAM size
'Encrypted': True, # Required for hibernation
'VolumeType': 'gp3'
}
}],
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Hibernate', 'Value': 'enabled'}]
}]
)
# Hibernate instance
ec2.stop_instances(
InstanceIds=['i-123'],
Hibernate=True # Enable hibernation
)
# Resume - applications continue from where they left off
ec2.start_instances(InstanceIds=['i-123'])
Use Cases:
- Long-running processes that need to pause
- Development environments
- Reducing startup time for large applications
🔍 Interviewer Notes: Testing knowledge of EC2 state management.
❌ Common Mistakes:
- Not encrypting root volume
- Root volume smaller than RAM
- Trying to hibernate with instance store
Q185: What are EC2 warm pools and how do they work?
Technical Answer: Warm pools maintain pre-initialized EC2 instances ready to join Auto Scaling groups.
import boto3
autoscaling = boto3.client('autoscaling')
# Create Auto Scaling group with warm pool
autoscaling.put_warm_pool(
AutoScalingGroupName='web-servers-asg',
PoolState='Hibernated', # or 'Stopped', 'Running'
MinSize=2,
MaxGroupPreparedCapacity=10,
InstanceReusePolicy={
'ReuseOnScaleIn': True # Return instances to warm pool
}
)
# Scale out - instances taken from warm pool (fast!)
autoscaling.set_desired_capacity(
AutoScalingGroupName='web-servers-asg',
DesiredCapacity=20
)
# Instances start from Hibernated state in seconds
Pool States:
Running: Instances running (fastest scale, highest cost)Stopped: Instances stopped (balanced)Hibernated: Instances hibernated (slowest, cheapest)
🔍 Interviewer Notes: Testing advanced Auto Scaling features.
❌ Common Mistakes:
- Not configuring instance reuse policy
- Wrong pool state for latency requirements
- Not considering warm pool costs
Q186: How do you implement EC2 instance metadata service v2 (IMDSv2)?
Technical Answer: IMDSv2 is a session-oriented, more secure replacement for IMDSv1.
Differences:
- IMDSv1: Simple HTTP GET (vulnerable to SSRF)
- IMDSv2: Session-based with token requirement
Enabling IMDSv2:
import boto3
ec2 = boto3.client('ec2')
# Launch with IMDSv2 required
ec2.run_instances(
ImageId='ami-xxx',
InstanceType='t3.medium',
MinCount=1,
MaxCount=1,
MetadataOptions={
'HttpTokens': 'required', # Force IMDSv2
'HttpPutResponseHopLimit': 1, # Container-aware
'HttpEndpoint': 'enabled'
}
)
# Modify existing instance
ec2.modify_instance_metadata_options(
InstanceId='i-123',
HttpTokens='required', # Enforce IMDSv2
HttpPutResponseHopLimit=1
)
Using IMDSv2 from instance:
#!/usr/bin/env python3
import requests
TOKEN_URL = 'http://169.254.169.254/latest/api/token'
METADATA_URL = 'http://169.254.169.254/latest/meta-data'
# Step 1: Get token (valid for up to 6 hours)
token = requests.put(
TOKEN_URL,
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=2
).text
# Step 2: Use token for metadata requests
headers = {'X-aws-ec2-metadata-token': token}
instance_id = requests.get(
f'{METADATA_URL}/instance-id',
headers=headers,
timeout=2
).text
iam_role = requests.get(
f'{METADATA_URL}/iam/security-credentials/',
headers=headers,
timeout=2
).text
print(f"Instance: {instance_id}, Role: {iam_role}")
Container Considerations:
- Containers share network namespace with host
- Increase hop limit to 2 for containers:
HttpPutResponseHopLimit: 2
🔍 Interviewer Notes: Testing security best practices.
❌ Common Mistakes:
- Not enforcing IMDSv2 (allows fallback to v1)
- Not updating hop limit for containers
- Hardcoding tokens
Q187: How do you implement EC2 instance connect for SSH access?
Technical Answer: EC2 Instance Connect provides temporary SSH keys without managing long-term keys.
import boto3
import json
import base64
def generate_ssh_command(instance_id, user='ec2-user'):
"""Generate one-time SSH command using Instance Connect"""
ec2 = boto3.client('ec2')
ec2_ic = boto3.client('ec2-instance-connect')
# Get instance details
instances = ec2.describe_instances(InstanceIds=[instance_id])
public_ip = instances['Reservations'][0]['Instances'][0]['PublicIpAddress']
# Generate temporary key pair
import subprocess
result = subprocess.run(
['ssh-keygen', '-t', 'rsa', '-f', '/tmp/temp_key', '-N', '', '-C', user],
capture_output=True
)
with open('/tmp/temp_key.pub', 'r') as f:
public_key = f.read().strip()
# Push public key to instance (valid for 60 seconds)
ec2_ic.send_ssh_public_key(
InstanceId=instance_id,
InstanceOsUser=user,
SSHPublicKey=public_key,
AvailabilityZone='us-east-1a'
)
# Return SSH command
return f"ssh -i /tmp/temp_key {user}@{public_ip}"
# Usage
ssh_cmd = generate_ssh_command('i-1234567890abcdef0')
print(f"Run: {ssh_cmd}")
Benefits:
- No long-term SSH keys to manage
- Integrates with IAM for access control
- CloudTrail logs all access
- Works with Session Manager as fallback
🔍 Interviewer Notes: Testing secure access patterns.
❌ Common Mistakes:
- Still using traditional key pairs
- Not enabling Instance Connect
- Not using IAM for SSH access control
Additional Core Questions Summary
Key EC2 Concepts Checklist:
- Instance types and families (T, M, C, R, I, G)
- Security groups and NACLs
- IAM roles and instance profiles
- Auto Scaling and Launch Templates
- Spot Instances and interruption handling
- EBS volume types (gp3, io2, st1, sc1)
- Reserved Instances and Savings Plans
- Nitro Enclaves
- Systems Manager for automation
Interview Quick Reference:
| Concept | Key Point |
|---|---|
| Security Groups | Stateful, allow rules only |
| NACLs | Stateless, allow and deny rules |
| Spot Instances | 90% discount, can be interrupted |
| gp3 vs gp2 | gp3 has better baseline (3000 IOPS) |
| Auto Scaling | Scale out on demand, scale in during quiet |
| EBS Encryption | Can encrypt at creation or migrate |
Senior / Principal — Amazon EC2 Real World Scenarios
Q188: Spot instance interruption — application not handling termination
Level: Senior
Scenario: A batch processing job runs on Spot Instances to save 90% cost. AWS sends a 2-minute interruption warning. The application doesn't handle it. Instances are terminated mid-job. Partially processed data is lost. Jobs must restart from scratch.
Impact: Lost work. Incomplete batches. Jobs take longer due to restarts. Cost savings negated by wasted compute.
Root Cause: Application doesn't monitor Spot interruption notices. No checkpointing. No graceful shutdown on termination warning.
Simple explanation: You're building a sandcastle. The tide is coming in (2-minute warning). You don't leave. The wave washes away your half-built castle.
Technical Answer:
- Monitor the Spot Instance interruption notice (IMDS metadata:
http://169.254.169.254/latest/meta-data/spot/instance-action). - Poll every 5 seconds; when
action=terminatewith 2-minute timeout, start graceful shutdown. - Checkpoint progress to durable storage (S3, EBS, DynamoDB) before termination.
- Use Spot Fleet with diversification across instance types and AZs to reduce interruption risk.
- Design jobs to be idempotent and resumable from checkpoints.
Code/Syntax Justification:
import requests
import time
import signal
INTERRUPTION_URL = "http://169.254.169.254/latest/meta-data/spot/instance-action"
def check_spot_interruption():
try:
resp = requests.get(INTERRUPTION_URL, timeout=1)
if resp.status_code == 200:
return resp.json() # {"action": "terminate", "time": "..."}
except requests.exceptions.RequestException:
pass # Not a Spot instance or no interruption
return None
# Poll in background thread
while True:
notice = check_spot_interruption()
if notice:
checkpoint_and_shutdown()
break
time.sleep(5)
Workflow Diagram:
Spot instance running job
|
v
AWS sends 2-minute interruption warning
|
v
Without handling: With handling:
Instance terminated immediately Poll IMDS -> detect action=terminate
| |
v v
Partial data lost Checkpoint progress to S3
Job restarts from scratch Graceful shutdown
|
v
Instance terminated
Job resumes from checkpoint
🔍 Behind the Question: Spot interruption handling, IMDS metadata, checkpointing, idempotent jobs, Spot Fleet diversification.
❌ The Red Flags: Not monitoring interruption notices; no checkpointing; non-idempotent jobs; single instance type/AZ.
Q189: EBS volume performance — gp3 vs io2 for database workloads
Level: Senior
Scenario: An EC2 instance runs PostgreSQL. The EBS volume (gp2) hits IOPS limits under write load. Database queries slow down. iowait is high. The team considers upgrading to io2 but is concerned about cost.
Impact: Database latency. Application timeouts. Poor user experience.
Root Cause: EBS volume type doesn't match workload IOPS/throughput needs. gp2 baseline IOPS is tied to volume size. Small volumes have low baseline IOPS.
Simple explanation: A water pipe is too narrow. Water flows slowly. You need a wider pipe (higher IOPS volume) or better flow management.
Technical Answer:
- gp3: baseline 3000 IOPS regardless of volume size, can provision up to 16,000 IOPS separately. Better price/performance than gp2.
- io2: up to 64,000 IOPS, sub-millisecond latency, for critical database workloads. Higher cost.
- Use gp3 for general purpose; io2 for high-performance databases.
- Monitor
VolumeReadOps,VolumeWriteOps,VolumeReadBytes,VolumeWriteBytes,BurstBalance. - Right-size volume: don't overprovision io2 if gp3 suffices.
Code/Syntax Justification:
# CloudFormation: gp3 with provisioned IOPS
EBSVolume:
Type: AWS::EC2::Volume
Properties:
VolumeType: gp3
Size: 100
Iops: 3000 # provisioned IOPS (separate from size)
Throughput: 125 # MB/s
Workflow Diagram:
gp2 (IOPS tied to size): gp3 (IOPS independent of size):
100 GB volume = 300 IOPS baseline 100 GB volume = 3000 IOPS baseline
| |
v v
IOPS exhausted under load Can provision additional IOPS
Database slow independently of volume size
🔍 Behind the Question: EBS volume types, IOPS provisioning, gp3 vs io2, database workload matching, monitoring.
❌ The Red Flags: gp2 for high-IOPS database; not monitoring EBS metrics; overprovisioning io2 unnecessarily; not understanding IOPS-size relationship.
Q190: Auto Scaling group — scale-in protection and instance termination
Level: Principal
Scenario: An Auto Scaling group scales in during quiet periods. It terminates instances that are actively processing long-running jobs (30-minute video transcodes). Jobs are interrupted. Output files incomplete.
Impact: Incomplete work. Failed jobs. Customer complaints.
Root Cause: ASG scale-in terminates instances without checking if they're processing work. No instance protection. No graceful drain.
Simple explanation: A factory closes for the day. Workers are still assembling products on the line. The factory shuts off power mid-assembly. Products are ruined.
Technical Answer:
- Enable scale-in protection on instances processing critical work.
- Use instance refresh with warm pools or lifecycle hooks to allow graceful shutdown.
- Create a custom lifecycle hook: ASG puts instance in
Terminating:Wait, application finishes work, then signals complete. - Use SQS + Lambda or Step Functions for long-running jobs instead of keeping them on EC2.
- Set cooldown periods appropriately to avoid thrashing.
Code/Syntax Justification:
# EC2 instance with scale-in protection
import boto3
ec2 = boto3.client('ec2')
# Enable scale-in protection
ec2.set_instance_protection(
AutoScalingGroupName='my-asg',
InstanceIds=['i-1234567890abcdef0'],
ScaleInProtection=True
)
# Disable when work is done
ec2.set_instance_protection(
AutoScalingGroupName='my-asg',
InstanceIds=['i-1234567890abcdef0'],
ScaleInProtection=False
)
Workflow Diagram:
ASG scale-in triggered
|
v
Select instance for termination
|
+-- No protection --> terminate immediately (jobs interrupted)
|
+-- Scale-in protection --> instance stays (jobs complete)
|
v
Disable protection after work done
|
v
ASG can now terminate
🔍 Behind the Question: Scale-in protection, lifecycle hooks, graceful shutdown, ASG termination policy.
❌ The Red Flags: No scale-in protection for critical workloads; terminating instances mid-job; no lifecycle hooks; long-running jobs on EC2 without SQS buffer.
Q191: Security group vs NACL — misconfigured outbound rules
Level: Senior
Scenario: An EC2 instance can't call an external API (e.g., Stripe, SendGrid). The security group allows outbound 443. But the Network ACL (NACL) outbound rules don't allow the response traffic back. Requests time out.
Impact: External API calls fail. Integrations broken. Application errors.
Root Cause: Security groups are stateful (allow return traffic automatically). NACLs are stateless (need explicit allow for both directions). Outbound NACL rule missing for ephemeral ports.
Simple explanation: Security guard lets you leave the building (outbound allowed). But the guard at the gate won't let you back in because there's no inbound rule for your return.
Technical Answer:
- Security groups: stateful, evaluate all rules, allow rules only. Return traffic automatically allowed.
- NACLs: stateless, evaluated in order, allow and deny rules. Need explicit outbound AND inbound rules for ephemeral ports (1024-65535).
- For outbound HTTPS: NACL outbound allow 443, AND inbound allow ephemeral ports (1024-65535) for return traffic.
- Use security groups primarily; NACLs for subnet-level isolation (e.g., blocking specific IP ranges).
- Test with VPC Reachability Analyzer.
Code/Syntax Justification:
// NACL outbound rule (allow HTTPS out)
{
"RuleNumber": 100,
"Protocol": "tcp",
"PortRange": "443",
"CidrBlock": "0.0.0.0/0",
"Action": "allow"
}
// NACL inbound rule (allow return traffic on ephemeral ports)
{
"RuleNumber": 100,
"Protocol": "tcp",
"PortRange": "1024-65535",
"CidrBlock": "0.0.0.0/0",
"Action": "allow"
}
Workflow Diagram:
Security Group (stateful): NACL (stateless):
Outbound 443 allowed Outbound 443 allowed
| |
v v
Return traffic auto-allowed Outbound request sent
| |
v v
Response received Return traffic blocked (no inbound ephemeral rule)
Connection works Request times out
🔍 Behind the Question: Security group vs NACL, stateful vs stateless, ephemeral ports, VPC troubleshooting.
❌ The Red Flags: Confusing SG and NACL; not allowing ephemeral ports in NACL inbound; using NACLs as primary security; not testing with Reachability Analyzer.
Q192: EC2 instance metadata — IMDSv2 vs IMDSv1
Level: Senior
Scenario: An EC2 instance retrieves IAM role credentials via IMDSv1 (http://169.254.169.254/latest/meta-data/iam/security-credentials/). A compromised container in the instance makes SSRF requests to the metadata endpoint and steals credentials.
Impact: Credential theft. Unauthorized AWS access. Lateral movement.
Root Cause: IMDSv1 allows unauthenticated GET requests. No session token required. SSRF attacks can read metadata.
Simple explanation: Anyone who walks into the building lobby can ask the receptionist for the master key. No ID check. IMDSv2 requires showing ID (session token) first.
Technical Answer:
- Use IMDSv2 (requires session token via PUT request, then GET with token header).
- Set
HttpTokenstorequired(notoptional) at instance launch. - Set
HttpPutResponseHopLimitto 1 (prevents container-to-container metadata access). - Use IAM roles for EC2 (not stored credentials).
- Rotate credentials automatically (IMDS handles rotation).
Code/Syntax Justification:
# IMDSv2: get session token first
import requests
# Step 1: Get token
token_response = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=2
)
token = token_response.text
# Step 2: Use token to get credentials
creds_response = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name',
headers={'X-aws-ec2-metadata-token': token},
timeout=2
)
Workflow Diagram:
IMDSv1 (insecure): IMDSv2 (secure):
GET metadata PUT /api/token -> get token
| |
v v
Credentials returned GET metadata + token header
No authentication Token validated, credentials returned
SSRF attack succeeds SSRF attack blocked (no token)
🔍 Behind the Question: IMDSv1 vs IMDSv2, SSRF protection, session tokens, HttpTokens required, IAM roles for EC2.
❌ The Red Flags: IMDSv1 (HttpTokens optional); no session token; HttpPutResponseHopLimit not set; stored credentials instead of IAM roles.
Q193: EC2 hibernation — preserving instance state
Level: Senior
Scenario: A development team stops EC2 instances at night to save cost. Each morning, instances reboot and re-run initialization scripts (10 minutes). Developers wait for instances to be ready. Lost in-memory state.
Impact: Wasted developer time. Slow startup. Lost unsaved state in memory.
Root Cause: Stopping instances wipes RAM. Instance reboots from scratch. No state preservation.
Simple explanation: You turn off your computer without saving. When you turn it on, all open apps are closed. You must reopen everything.
Technical Answer:
- Enable EC2 hibernation: saves RAM to EBS root volume on stop. Restores state on start.
- Instances start faster (no re-initialization). In-memory state preserved.
- Requirements: EBS root volume encrypted, instance size sufficient, supported AMI.
- Not suitable for workloads with >16GB RAM (hibernation slower) or short-lived instances.
- Cost: pay for EBS storage of hibernated RAM + instance stopped (no compute charge).
Code/Syntax Justification:
# Enable hibernation on launch
ec2.run_instances(
ImageId='ami-12345678',
InstanceType='m5.large',
MaxCount=1,
MinCount=1,
HibernationOptions={'Configured': True},
BlockDeviceMappings=[{
'DeviceName': '/dev/sda1',
'Ebs': {'Encrypted': True, 'VolumeType': 'gp3'}
}]
)
Workflow Diagram:
Stop instance (no hibernation): Stop instance (hibernation):
RAM wiped to disk RAM saved to EBS (encrypted)
| |
v v
Start: re-initialize (10 min) Start: restore RAM (30 sec)
| |
v v
Developer waits Developer productive immediately
🔍 Behind the Question: EC2 hibernation, state preservation, EBS encryption requirement, cost trade-offs.
❌ The Red Flags: Hibernation on unencrypted EBS; hibernating instances >16GB RAM; hibernating short-lived instances; not understanding stopped vs hibernated cost.
Q194: EC2 launch template vs launch configuration
Level: Principal
Scenario: A team uses Launch Configurations (legacy) for Auto Scaling. They want to use a newer instance type (T3 instead of T2) and add a new security group. Launch Configurations are immutable — can't update. Must create new LC and update ASG.
Impact: Slow iteration. Can't easily update ASG configuration. No versioning.
Root Cause: Launch Configurations are legacy and immutable. Launch Templates are versionable and support more features (T2/T3 unlimited, tags, etc.).
Simple explanation: A Launch Configuration is a printed form. To change one word, you print a new form. A Launch Template is a Google Doc — versioned, editable, shareable.
Technical Answer:
- Use Launch Templates (not Launch Configurations) for new Auto Scaling groups.
- Launch Templates support versioning — create new version, update ASG to use specific version.
- Supports more features: T2/T3 CPU credits, EBS encryption, tagging, capacity rebalancing.
- Can set default version in ASG; rollback by pointing to previous version.
- Migrate existing ASGs from LC to LT.
Code/Syntax Justification:
# Create launch template version
response = ec2.create_launch_template_version(
LaunchTemplateId='lt-1234567890abcdef0',
SourceVersion='1',
LaunchTemplateData={
'InstanceType': 't3.medium',
'SecurityGroupIds': ['sg-new'],
'ImageId': 'ami-new'
}
)
new_version = response['LaunchTemplateVersion']['VersionNumber']
# Update ASG to use new version
asg.update_auto_scaling_group(
AutoScalingGroupName='my-asg',
LaunchTemplate={'LaunchTemplateId': 'lt-1234567890abcdef0', 'Version': str(new_version)}
)
Workflow Diagram:
Launch Configuration (legacy): Launch Template (versioned):
Immutable Version 1 -> v2 -> v3
| |
v v
Change = create new LC Change = create new version
Update ASG manually Update ASG to use version
No rollback versioning Rollback = point to previous version
🔍 Behind the Question: Launch Template vs Launch Configuration, versioning, ASG updates, rollback.
❌ The Red Flags: Using Launch Configurations (legacy); no versioning; not using Launch Templates for new ASGs; can't rollback easily.
Senior / Principal — Amazon EC2 Real World Scenarios (Continued)
Q195: Instance store vs EBS — data persistence choice
Level: Senior
Scenario: A team launches EC2 instances with instance store (ephemeral) storage for a database. The instance is stopped/restarted. All data is lost because instance store doesn't persist across stop/start.
Impact: Data loss. Database unavailable. Recovery from backup needed.
Root Cause: Instance store is tied to the host. Data is lost when the instance is stopped, terminated, or the host fails. Not suitable for databases or stateful workloads.
Simple explanation: Instance store is like scratch paper — it disappears when you throw it away. EBS is like a notebook — it persists.
Technical Answer:
- Use EBS volumes for any data that must persist (databases, user files, application state).
- Use instance store only for temporary data (cache, temp files, load balancer buffers) that can be recreated.
- Enable EBS encryption at rest for sensitive data.
- Use EBS snapshots for backup and point-in-time recovery.
- For databases, consider RDS (managed) instead of self-managed EC2 + EBS.
Code/Syntax Justification:
# EBS volume (persistent)
ec2.create_volume(
AvailabilityZone='us-east-1a',
Size=100,
VolumeType='gp3',
Encrypted=True
)
# Instance store (ephemeral) - specified in block device mapping, no separate creation
Workflow Diagram:
Instance store: EBS volume:
Data lost on stop/terminate Data persists across stop/start
| |
v v
Database data lost Database data intact
| |
v v
Recovery from backup No recovery needed
🔍 Behind the Question: Instance store vs EBS, persistence, stop/start behavior, EBS encryption, snapshots.
❌ The Red Flags: Database on instance store; no EBS encryption; no EBS snapshots for backup.
Q196: EBS snapshot — backup and point-in-time recovery
Level: Senior
Scenario: A production EC2 instance's EBS volume is accidentally deleted. The team needs to recover data. They have daily EBS snapshots but the last snapshot is 24 hours old. They lose 24 hours of data.
Impact: Data loss (24 hours). Recovery incomplete. Business impact.
Root Cause: Backup frequency (daily snapshots) doesn't meet Recovery Point Objective (RPO). No continuous backup or more frequent snapshots.
Simple explanation: You back up your files every night at midnight. You delete a file at 2 PM. The last backup is from midnight. You lost 14 hours of work.
Technical Answer:
- Schedule EBS snapshots more frequently (e.g., every 4-6 hours) for critical volumes.
- Use Amazon Data Lifecycle Manager (DLM) to automate snapshot creation and retention.
- Cross-region snapshot copy for disaster recovery.
- Test snapshot restore regularly — backup is useless without verified restore.
- Consider EBS Multi-Attach or EBS Direct APIs for advanced backup patterns.
Code/Syntax Justification:
# Create EBS snapshot
ec2.create_snapshot(
VolumeId='vol-1234567890abcdef0',
Description='Production DB snapshot'
)
# DLM policy (automated snapshots)
# Via DLM console/CLI: target resource type VOLUME, schedule every 6 hours, retain 7 snapshots
Workflow Diagram:
Daily snapshots: Frequent snapshots (DLM):
Snapshot at midnight Snapshots every 4 hours
| |
v v
Data deleted at 2 PM Data deleted at 2 PM
| |
v v
Restore to midnight (lose 24h) Restore to 12 PM (lose 2h)
24 hours data loss 2 hours data loss
🔍 Behind the Question: EBS snapshots, DLM, RPO, backup frequency, disaster recovery.
❌ The Red Flags: Daily snapshots only; no DLM automation; not testing restores; no cross-region copy for DR.
Q197: AMI — golden image and fast provisioning
Level: Senior
Scenario: A team launches EC2 instances from a base Amazon Linux AMI and runs user-data scripts to install dependencies, configure security, and deploy the application. Each launch takes 20 minutes. Auto scaling is slow to respond to traffic spikes.
Impact: Slow auto-scaling. Instances not ready during traffic spikes. Inconsistent configurations.
Root Cause: User-data scripts run at launch time. Inconsistent execution. Long bootstrapping time.
Simple explanation: You build a cake from scratch every time you want one. You should bake a few ahead of time (golden image) and just frost them when needed.
Technical Answer:
- Create golden AMI (Amazon Machine Image) with all dependencies, security patches, and application pre-installed.
- Use Image Builder (EC2 Image Builder) to automate AMI creation and testing.
- Launch instances from golden AMI — user-data only for environment-specific config.
- Reduces launch time from 20 minutes to 2-3 minutes.
- Enables faster auto-scaling and consistent configurations.
Code/Syntax Justification:
# Create AMI from running instance
ec2.create_image(
InstanceId='i-1234567890abcdef0',
Name='production-web-server-v1.2',
Description='Golden image with app pre-installed'
)
# Launch from AMI
ec2.run_instances(
ImageId='ami-0abcdef1234567890',
InstanceType='m6i.large',
MinCount=1,
MaxCount=10
)
Workflow Diagram:
User-data bootstrap: Golden AMI:
Launch instance Launch from AMI
| |
v v
Run install scripts (20 min) Instance ready (2-3 min)
| |
v v
Application ready Application ready
Slow auto-scaling Fast auto-scaling
🔍 Behind the Question: AMI, golden image, EC2 Image Builder, launch time, auto-scaling speed.
❌ The Red Flags: No golden image; heavy user-data at launch; inconsistent configurations; slow auto-scaling response.
Q198: Spot Fleet — diversification and interruption handling
Level: Principal
Scenario: A batch processing job uses Spot Instances. All instances are of one type (m5.large) in one AZ. AWS interrupts all of them simultaneously due to capacity reclamation. The job fails. No diversification.
Impact: Job failure. Lost compute capacity. No redundancy.
Root Cause: No diversification across instance types and AZs. Single point of failure for Spot capacity.
Simple explanation: You rent all your warehouse space in one building. The building closes. You have nowhere to store goods.
Technical Answer:
- Use Spot Fleet with diversification across multiple instance types and AZs.
- Set allocation strategy: capacity-optimized (lowest interruption risk) or lowest-price.
- Handle interruption notices (2-minute warning) via IMDS metadata.
- Checkpoint work to durable storage (S3) for resumption.
- Use capacity-optimized-prioritized to define preferred instance types.
Code/Syntax Justification:
# Spot Fleet request with diversification
ec2.request_spot_fleet(
SpotFleetRequestConfig={
'AllocationStrategy': 'capacity-optimized',
'TargetCapacity': 100,
'LaunchSpecifications': [
{'InstanceType': 'm5.large', 'AvailabilityZone': 'us-east-1a', 'WeightedCapacity': 1},
{'InstanceType': 'm5.xlarge', 'AvailabilityZone': 'us-east-1b', 'WeightedCapacity': 2},
{'InstanceType': 'c5.large', 'AvailabilityZone': 'us-east-1c', 'WeightedCapacity': 1},
]
}
)
Workflow Diagram:
No diversification: Spot Fleet diversification:
All instances: m5.large in 1AZ Instance types: m5.large, m5.xlarge, c5.large
| |
v v
AWS interrupts m5.large capacity AWS interrupts one type/AZ
| |
v v
All compute lost Other instances continue
Job fails Job continues (reduced capacity)
🔍 Behind the Question: Spot Fleet, diversification, instance types, AZs, interruption handling.
❌ The Red Flags: One instance type in one AZ; no diversification; no interruption handling; no checkpointing.
Q199: Placement groups — cluster, spread, partition
Level: Senior
Scenario: A team runs a high-performance computing (HPC) workload. Instances are scattered across different AZs. Network latency between nodes is high. MPI jobs are slow due to inter-node communication.
Impact: Poor application performance. High inter-node latency. Wasted compute.
Root Cause: No placement strategy. Instances launched without placement group. Network topology not optimized.
Simple explanation: Team members are in different buildings. They spend all day walking between buildings to talk. They should be in the same room.
Technical Answer:
- Use cluster placement group for low-latency, high-throughput inter-node communication (same AZ, same rack).
- Use spread placement group for critical instances that must be isolated (different racks, no shared hardware).
- Use partition placement group for large distributed workloads (HDFS, Cassandra, Kafka) — divides instances into logical partitions.
- Choose placement group strategy based on workload: HPC (cluster), critical isolation (spread), distributed storage (partition).
- Placement groups only work with specific instance types.
Code/Syntax Justification:
# Create cluster placement group
ec2.create_placement_group(
GroupName='hpc-cluster',
Strategy='cluster'
)
# Launch instances into placement group
ec2.run_instances(
Placement={'GroupName': 'hpc-cluster'},
InstanceType='c5n.18xlarge', # enhanced networking
MinCount=10,
MaxCount=10
)
Workflow Diagram:
No placement group: Cluster placement group:
Instances scattered across AZs Instances in same AZ, same rack
| |
v v
High inter-node latency Low-latency, high-throughput
| |
v v
MPI jobs slow MPI jobs fast
🔍 Behind the Question: Placement groups, cluster/spread/partition, inter-node latency, enhanced networking.
❌ The Red Flags: No placement group for HPC; spread placement for HPC (wrong strategy); instance types not compatible with placement groups.
Q200: Enhanced networking (ENA, EFA) — network performance
Level: Senior
Scenario: A team runs a distributed application (MPI, machine learning training) on EC2. Network throughput between instances is low. CPU is underutilized because nodes wait for network data.
Impact: Poor application performance. Network-bound. Wasted compute.
Root Cause: Instances don't use enhanced networking (ENA or EFA). Standard virtualized network has lower throughput and higher latency.
Simple explanation: You're moving water through a garden hose. You need a fire hose for high throughput. Standard networking is the garden hose; ENA/EFA is the fire hose.
Technical Answer:
- Use Enhanced Networking (ENA) for improved network throughput and lower latency (most modern instance types).
- Use Elastic Fabric Adapter (EFA) for HPC and ML workloads requiring OS-bypass, low-latency, high-throughput inter-node communication (MPI).
- Choose instance types with enhanced networking (c5n, p4d, etc.).
- Enable EFA at launch:
Options={'Efa': {'Enabled': True}}. - Measure with iperf3 between instances.
Code/Syntax Justification:
# Launch with EFA (Elastic Fabric Adapter)
ec2.run_instances(
ImageId='ami-0abcdef1234567890',
InstanceType='p4d.24xlarge',
MinCount=8,
MaxCount=8,
Options={
'Efa': {'Enabled': True}
},
Placement={'GroupName': 'mpi-cluster'}
)
Workflow Diagram:
Standard networking: ENA/EFA enhanced networking:
Virtualized network OS-bypass, low latency
| |
v v
Lower throughput, higher latency High throughput, low latency
| |
v v
Application network-bound Application compute-bound (optimal)
🔍 Behind the Question: Enhanced networking, ENA, EFA, MPI, OS-bypass, network performance.
❌ The Red Flags: Standard networking for HPC/ML; no EFA for MPI workloads; not measuring network throughput.
Q201: T2/T3/T3a burstable instances — CPU credits
Level: Senior
Scenario: A team runs a development server on T3 instances. CPU credits are exhausted. The instance is limited to baseline performance. Application becomes slow.
Impact: Application slow. Unpredictable performance. Confusion about why.
Root Cause: T2/T3/T3a are burstable instances. They accumulate CPU credits when idle and spend them when busy. Once credits are exhausted, performance drops to baseline.
Simple explanation: You have a prepaid phone card. You use all the minutes. Calls are now limited to a slow rate until you buy more.
Technical Answer:
- Monitor CPU credit balance (
CPUCreditBalanceCloudWatch metric). - Understand baseline performance (percentage of one vCPU).
- Use T3 Unlimited mode to allow bursting beyond credits (pays for excess).
- For consistent workloads, use M-series (m5, m6i) instead of burstable instances.
- Right-size based on actual CPU utilization patterns.
Code/Syntax Justification:
# Launch T3 Unlimited (allows bursting beyond credits)
ec2.run_instances(
InstanceType='t3.medium',
MinCount=1,
MaxCount=1,
CreditSpecification={'CpuCredits': 'unlimited'}
)
Workflow Diagram:
T3 Standard (limited): T3 Unlimited:
CPU credits exhausted CPU credits exhausted
| |
v v
Performance limited to baseline Can burst beyond credits (pay excess)
| |
v v
Application slow Application maintains performance
🔍 Behind the Question: Burstable instances, CPU credits, T3 Unlimited, baseline performance, right-sizing.
❌ The Red Flags: T3 instances for consistent high-CPU workloads; not monitoring CPU credits; not using Unlimited for burstable needs.
Q202: Dedicated Instances and Dedicated Hosts — compliance
Level: Principal
Scenario: A financial services company has compliance requirements that their workloads must run on hardware dedicated to them (no sharing with other AWS customers). Standard EC2 instances run on shared hardware.
Impact: Compliance violation. Cannot pass audit. Business cannot operate.
Root Cause: Standard EC2 instances may share physical hardware with other AWS customers (hardware virtualization isolation, but same physical server).
Simple explanation: You live in an apartment building (shared hardware). Compliance requires a single-family home (dedicated hardware).
Technical Answer:
- Use Dedicated Instances: run on hardware dedicated to a single AWS account.
- Use Dedicated Hosts: physical server fully dedicated to your use; you can bring your own licenses (BYOL) for Windows/SQL Server/Oracle.
- Dedicated Hosts give visibility into sockets/cores and allow license cost optimization.
- Higher cost than standard instances. Use only when compliance requires.
- Can combine with Auto Scaling (Dedicated Instances) or host placement affinity (Dedicated Hosts).
Code/Syntax Justification:
# Dedicated Instance
ec2.run_instances(
InstanceType='m5.large',
Placement={'Tenancy': 'dedicated'},
MinCount=1,
MaxCount=1
)
# Dedicated Host allocation
response = ec2.allocate_hosts(
InstanceType='m5.large',
AvailabilityZone='us-east-1a',
Quantity=2
)
host_id = response['HostIds'][0]
# Launch onto specific Dedicated Host
ec2.run_instances(
InstanceType='m5.large',
Placement={'HostId': host_id, 'Tenancy': 'host'},
MinCount=1,
MaxCount=1
)
Workflow Diagram:
Standard EC2: Dedicated Instance/Host:
Hardware shared with other AWS Hardware dedicated to your account
customers |
| |
v v
Compliance violation (financial) Compliance satisfied
| |
v v
Cannot pass audit Pass audit, operate legally
🔍 Behind the Question: Dedicated Instances, Dedicated Hosts, compliance, BYOL, hardware isolation.
❌ The Red Flags: Standard EC2 for compliance-requiring workloads; not understanding Dedicated Host vs Instance; using Dedicated for non-compliance workloads (waste of money).
Q203: EC2 hibernation — preserving memory state
Level: Senior
Scenario: A team stops EC2 instances at night to save cost. Each morning, instances reboot and re-run initialization scripts (10 minutes). Developers wait. Unsaved in-memory state is lost.
Impact: Wasted developer time. Slow startup. Lost in-memory state.
Root Cause: Stopping instances wipes RAM. Instance reboots from scratch. No state preservation.
Simple explanation: You turn off your computer without saving. When you turn it on, all open apps are closed. You must reopen everything.
Technical Answer:
- Enable EC2 hibernation: saves RAM to EBS root volume on stop. Restores state on start.
- Instances start faster (no re-initialization). In-memory state preserved.
- Requirements: EBS root volume encrypted, instance size sufficient, supported AMI.
- Not suitable for workloads with >16GB RAM (hibernation slower) or short-lived instances.
- Cost: pay for EBS storage of hibernated RAM + instance stopped (no compute charge).
Code/Syntax Justification:
# Enable hibernation on launch
ec2.run_instances(
ImageId='ami-12345678',
InstanceType='m5.large',
MaxCount=1,
MinCount=1,
HibernationOptions={'Configured': True},
BlockDeviceMappings=[{
'DeviceName': '/dev/sda1',
'Ebs': {'Encrypted': True, 'VolumeType': 'gp3'}
}]
)
Workflow Diagram:
Stop (no hibernation): Stop (hibernation):
RAM wiped to disk RAM saved to EBS (encrypted)
| |
v v
Start: re-initialize (10 min) Start: restore RAM (30 sec)
| |
v v
Developer waits Developer productive immediately
🔍 Behind the Question: EC2 hibernation, state preservation, EBS encryption requirement, cost trade-offs.
❌ The Red Flags: Hibernation on unencrypted EBS; hibernating instances >16GB RAM; hibernating short-lived instances; not understanding stopped vs hibernated cost.
Q204: EC2 Instance Metadata Service (IMDS) — IMDSv2 security
Level: Senior
Scenario: An application retrieves IAM role credentials from the instance metadata service. A vulnerable web application on the instance allows SSRF (Server-Side Request Forgery). An attacker retrieves credentials from http://169.254.169.254/latest/meta-data/iam/security-credentials/.
Impact: Credential theft. Unauthorized AWS access. Lateral movement.
Root Cause: IMDSv1 allows unauthenticated GET requests. No session token required. SSRF attacks can read metadata.
Simple explanation: Anyone who walks into the building lobby can ask the receptionist for the master key. No ID check. IMDSv2 requires showing ID (session token) first.
Technical Answer:
- Use IMDSv2 (requires session token via PUT request, then GET with token header).
- Set
HttpTokenstorequired(notoptional) at instance launch. - Set
HttpPutResponseHopLimitto 1 (prevents container-to-container metadata access). - Use IAM roles for EC2 (not stored credentials).
- Rotate credentials automatically (IMDS handles rotation).
Code/Syntax Justification:
# IMDSv2: get session token first
import requests
# Step 1: Get token
token_response = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=2
)
token = token_response.text
# Step 2: Use token to get credentials
creds_response = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name',
headers={'X-aws-ec2-metadata-token': token},
timeout=2
)
Workflow Diagram:
IMDSv1 (insecure): IMDSv2 (secure):
GET metadata PUT /api/token -> get token
| |
v v
Credentials returned GET metadata + token header
No authentication Token validated, credentials returned
SSRF attack succeeds SSRF attack blocked (no token)
🔍 Behind the Question: IMDSv1 vs IMDSv2, SSRF protection, session tokens, HttpTokens required, IAM roles for EC2.
❌ The Red Flags: IMDSv1 (HttpTokens optional); no session token; HttpPutResponseHopLimit not set; stored credentials instead of IAM roles.
Q205: EC2 Auto Scaling — target tracking vs step scaling
Level: Senior
Scenario: An Auto Scaling group uses simple scaling (add 2 instances when CPU > 70%). During traffic spikes, it adds instances too slowly or too many. The group oscillates (adds then removes).
Impact: Poor scaling response. Cost waste or performance issues.
Root Cause: Simple scaling policies don't adapt to the rate of change. Target tracking maintains a specific metric value more smoothly.
Simple explanation: You adjust the shower temperature by turning the knob a fixed amount each time. You overshoot (too hot) then undershoot (too cold). Target tracking sets a target temperature and adjusts smoothly.
Technical Answer:
- Use target tracking scaling policies (e.g., keep CPU at 50%). ASG adds/removes instances to maintain target.
- Use step scaling for predictable metric ranges (add 2 instances at 70%, add 4 at 80%).
- Combine with scheduled scaling for predictable patterns (business hours).
- Set cooldown periods appropriately to avoid thrashing.
- Monitor
CPUUtilizationandGroupInServiceInstances.
Code/Syntax Justification:
# Target tracking scaling policy
applicationautoscaling.put_scaling_policy(
PolicyName='cpu-target-tracking',
ServiceNamespace='ec2',
ResourceId='autoScalingGroup/my-asg',
ScalableDimension='autoscaling:autoScalingGroup:DesiredCapacity',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'PredefinedMetricSpecification': {'PredefinedMetricType': 'ASGAverageCPUUtilization'},
'TargetValue': 50.0
}
)
Workflow Diagram:
Simple scaling: Target tracking:
CPU > 70% -> add 2 instances Target: CPU = 50%
| |
v v
CPU > 70% again -> add 2 more CPU rises -> add instances
| |
v v
Oscillates (too many/few) Smoothly maintains 50%
🔍 Behind the Question: Auto Scaling policies, target tracking vs step scaling, cooldown, oscillation.
❌ The Red Flags: Simple scaling only; no cooldown or too short cooldown; not using target tracking for CPU-based scaling.
Q206: EC2 Reserved Instances and Savings Plans — cost commitment
Level: Principal
Scenario: A team runs steady-state workloads on On-Demand EC2 instances 24/7. The monthly EC2 bill is high. They could save money with commitment but haven't analyzed.
Impact: High EC2 cost. Overpaying for predictable workloads.
Root Cause: Using On-Demand pricing for steady-state workloads. No Reserved Instances or Savings Plans.
Simple explanation: You book a hotel room at walk-in rate every night. You could book a monthly rate for 30% less.
Technical Answer:
- Use Savings Plans (EC2 Instance Savings Plans or Compute Savings Plans) for 1- or 3-year commitments (up to 72% savings).
- EC2 Instance Savings Plans: specific instance family in a region (less flexible).
- Compute Savings Plans: any EC2 instance, any region, plus Fargate/Lambda (more flexible).
- Reserved Instances: zonal or regional, convertible or standard (more complex, legacy).
- Analyze usage with AWS Cost Explorer before committing.
Code/Syntax Justification:
# Purchase Savings Plan (via AWS Cost Explorer / billing console)
# Via API:
client.create_savings_plan(
SavingsPlanOfferingId='offering-12345',
Commitment='Hourly:ComputeSavingsPlans:0.05' # $0.05/hour commitment
)
Workflow Diagram:
On-Demand: Savings Plans:
Pay full hourly rate Commit to $X/hour for 1-3 years
| |
v v
High monthly bill Up to 72% savings
No commitment Commitment required
🔍 Behind the Question: Savings Plans, Reserved Instances, cost commitment, cost optimization, AWS Cost Explorer.
❌ The Red Flags: On-Demand for steady-state workloads; no cost analysis; not using Savings Plans for predictable workloads.
Q207: EC2 Systems Manager (SSM) — patch management
Level: Senior
Scenario: A team manages 50 EC2 instances. They manually log into each to apply security patches. Patching is inconsistent. Some instances are missing critical patches. Security audit fails.
Impact: Security vulnerabilities. Inconsistent patch state. Audit failure.
Root Cause: Manual patching. No automated patch management. No visibility into patch state.
Simple explanation: You update 50 apps on your phone one by one. You miss some. Your phone is vulnerable.
Technical Answer:
- Use EC2 Systems Manager (SSM) Patch Manager for automated patching.
- Create patch baselines (approved/rejected patches).
- Use maintenance windows to define patching schedules.
- Use SSM documents (automation) for consistent patching across instances.
- Monitor patch compliance via SSM compliance dashboard.
Code/Syntax Justification:
# SSM patch baseline
ssm.create_patch_baseline(
Name='Production-Baseline',
OperatingSystem='AMAZON_LINUX_2',
ApprovalRules={
'PatchRules': [{
'PatchFilterGroup': {
'PatchFilters': [
{'Key': 'CLASSIFICATION', 'Values': ['Security']},
{'Key': 'SEVERITY', 'Values': ['Critical', 'High']}
]
},
'ApproveAfterDays': 7
}]
}
)
Workflow Diagram:
Manual patching: SSM Patch Manager:
Log into each instance Patch baseline defines approved patches
| |
v v
Inconsistent patch state Maintenance window schedules patching
| |
v v
Security audit fails All instances compliant
Compliance dashboard visible
🔍 Behind the Question: SSM Patch Manager, patch baselines, maintenance windows, compliance, automation.
❌ The Red Flags: Manual patching; no patch baseline; no maintenance windows; not monitoring compliance.
Q208: EC2 monitoring — CloudWatch detailed monitoring
Level: Senior
Scenario: A team has basic EC2 monitoring (5-minute intervals). During an incident, CPU spikes for 2 minutes between data points. The team doesn't see the spike. They miss the root cause.
Impact: Missed incidents. Slow MTTDR. Incomplete picture.
Root Cause: Basic monitoring is 5-minute intervals. Detailed monitoring is 1-minute intervals. Critical short-lived events are missed.
Simple explanation: You check your security camera every 5 minutes. A burglar enters and leaves in 2 minutes. You don't see them.
Technical Answer:
- Enable detailed monitoring (1-minute intervals) on EC2 instances for critical workloads.
- Basic monitoring is free; detailed monitoring costs extra per instance per month.
- Use CloudWatch metrics: CPUUtilization, NetworkIn/Out, DiskReadOps/WriteOps, StatusCheckFailed.
- Create CloudWatch alarms on detailed metrics for faster detection.
- Combine with CloudWatch Logs for application-level visibility.
Code/Syntax Justification:
# Enable detailed monitoring
ec2.monitor_instances(InstanceIds=['i-1234567890abcdef0'])
# CloudWatch alarm on CPU
cloudwatch.put_metric_alarm(
AlarmName='HighCPU',
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistic='Average',
Period=60, # 1 minute (requires detailed monitoring)
Threshold=80,
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=3
)
Workflow Diagram:
Basic monitoring (5 min): Detailed monitoring (1 min):
CPU spike at 10:02, ends 10:04 CPU spike at 10:02, ends 10:04
| |
v v
Data points at 10:00, 10:05 Data points at 10:02, 10:03, 10:04
Misses the spike Catches the spike
🔍 Behind the Question: EC2 detailed monitoring, CloudWatch metrics, monitoring intervals, alarms.
❌ The Red Flags: Basic monitoring for critical workloads; no CloudWatch alarms; not understanding 5-min vs 1-min intervals.
Q209: EC2 status checks — system vs instance
Level: Senior
Scenario: An EC2 instance shows Status Check Failed. The team doesn't know if it's the underlying host (system check) or the instance OS/application (instance check). They reboot when they should stop/start, or vice versa.
Impact: Wrong remediation action. Longer downtime.
Root Cause: Not understanding the difference between system status checks (host) and instance status checks (OS/application).
Simple explanation: A car won't start. Is it the engine (system) or the key (instance)? You need to know which to fix.
Technical Answer:
- System status check: detects issues with the underlying host (hardware, network, AWS side). Fix: stop/start instance (moves to new host).
- Instance status check: detects issues with the instance itself (OS, application, misconfiguration). Fix: reboot or troubleshoot instance.
- Both checks must pass for instance to be considered healthy.
- Use EC2 Auto Scaling health checks to replace instances failing status checks.
- Monitor
StatusCheckFailed,StatusCheckFailed_Instance,StatusCheckFailed_SystemCloudWatch metrics.
Code/Syntax Justification:
# Check status checks
response = ec2.describe_instance_status(InstanceIds=['i-1234567890abcdef0'])
for status in response['InstanceStatuses']:
print(status['InstanceState']['Name'])
print(status['SystemStatus']['Status']) # ok/impaired/insufficient-data
print(status['InstanceStatus']['Status']) # ok/impaired/insufficient-data
Workflow Diagram:
Status Check Failed:
|
+-- System Status Check failed --> AWS host issue --> stop/start (new host)
|
+-- Instance Status Check failed --> OS/application issue --> reboot/troubleshoot
🔍 Behind the Question: Status checks, system vs instance, remediation actions, CloudWatch metrics.
❌ The Red Flags: Rebooting for system check failures; stop/start for instance check failures; not distinguishing the two check types.
Q210: EC2 capacity reservation — guaranteed capacity
Level: Principal
Scenario: A team needs to launch 100 instances during a product launch event. On-Demand capacity is unavailable in the AZ. Instances fail to launch. The launch is delayed.
Impact: Launch delay. Lost revenue. Poor customer experience.
Root Cause: No capacity reservation. On-Demand capacity is first-come-first-served and can be unavailable during high demand.
Simple explanation: You go to a restaurant at peak hour. No tables available. You should have reserved a table.
Technical Answer:
- Use Capacity Reservations to reserve EC2 capacity in a specific AZ.
- Reservations ensure capacity is available when you need it.
- Can be shared across accounts (Capacity Reservation groups).
- Combine with Auto Scaling (capacity-rebalanced) for Spot + On-Demand mix.
- Pay for reserved capacity even if not used (like On-Demand pricing for reserved instances).
Code/Syntax Justification:
# Create Capacity Reservation
ec2.create_capacity_reservation(
InstanceType='m6i.large',
InstancePlatform='Linux/UNIX',
AvailabilityZone='us-east-1a',
InstanceCount=100
)
# Run instances into Capacity Reservation
ec2.run_instances(
InstanceType='m6i.large',
MinCount=100,
MaxCount=100,
CapacityReservationSpecification={
'CapacityReservationPreference': 'open',
'CapacityReservationTarget': {
'CapacityReservationId': 'cr-1234567890abcdef0'
}
}
)
Workflow Diagram:
No Capacity Reservation: Capacity Reservation:
Launch 100 instances Reserve 100 instances in advance
| |
v v
Insufficient capacity Capacity guaranteed
| |
v v
Launch delayed Launch succeeds on time
🔍 Behind the Question: Capacity Reservations, guaranteed capacity, AZ capacity, launch planning.
❌ The Red Flags: No capacity reservation for critical launches; not understanding capacity scarcity; not combining with Auto Scaling.
Senior / Principal — Amazon EC2 Real World Scenarios (Continued)
Q211: VPC networking — subnets, route tables, IGW, NAT Gateway
Level: Senior
Scenario: A team launches EC2 instances in a private subnet. The instances can't reach the internet to download updates. They have no internet access but need to call external APIs.
Impact: Instances can't download patches or call external services. Application broken.
Root Cause: Private subnet has no route to a NAT Gateway or Internet Gateway. No path to the internet.
Simple explanation: You're in a room with no door to the outside. You can't get out to buy supplies.
Technical Answer:
- Private subnets route traffic to a NAT Gateway (in a public subnet) for outbound internet access.
- Public subnets route to an Internet Gateway (IGW) for bidirectional internet access.
- Route tables direct traffic: private subnet -> NAT Gateway; public subnet -> IGW.
- NAT Gateway allows outbound but blocks inbound initiated connections.
- Security groups and NACLs must also allow the traffic.
Code/Syntax Justification:
# Route table for private subnet
# Destination: 0.0.0.0/0 -> Target: nat-gateway-id
# Route table for public subnet
# Destination: 0.0.0.0/0 -> Target: igw-id
Workflow Diagram:
Private subnet without NAT: Private subnet with NAT:
No route to internet Route 0.0.0.0/0 -> NAT Gateway
| |
v v
No internet access Outbound via NAT Gateway
🔍 Behind the Question: VPC subnets, route tables, Internet Gateway, NAT Gateway, public vs private subnets.
❌ The Red Flags: Private subnet with no NAT Gateway; public subnet with sensitive instances; missing route table entries.
Q212: Security Groups vs NACLs — stateful vs stateless
Level: Senior
Scenario: A team configures a Security Group to allow inbound port 443. They also configure a NACL. Outbound response traffic is blocked because the NACL is stateless and doesn't allow the ephemeral port range back in.
Impact: Requests time out. Application can't complete outbound calls.
Root Cause: NACLs are stateless — require explicit allow rules for both inbound and outbound, including ephemeral ports (1024-65535) for return traffic.
Simple explanation: A security guard lets you leave the building (outbound allowed) but won't let you back in because there's no inbound rule for your return.
Technical Answer:
- Security Groups are stateful — allow rules automatically permit return traffic.
- NACLs are stateless — need explicit inbound AND outbound rules.
- NACL outbound: allow port 443 to 0.0.0.0/0.
- NACL inbound: allow ephemeral ports (1024-65535) from 0.0.0.0/0 for return traffic.
- Process: Security Group first, then NACL (both must allow).
Code/Syntax Justification:
# NACL outbound rule: allow HTTPS out
# Rule 100: TCP 443, 0.0.0.0/0, ALLOW
# NACL inbound rule: allow ephemeral ports for return
# Rule 100: TCP 1024-65535, 0.0.0.0/0, ALLOW
Workflow Diagram:
Security Group (stateful): NACL (stateless):
Outbound 443 allowed Outbound 443 allowed
| |
v v
Return traffic auto-allowed Return traffic blocked (no inbound ephemeral rule)
Connection works Request times out
🔍 Behind the Question: Security Groups vs NACLs, stateful vs stateless, ephemeral ports, rule evaluation order.
❌ The Red Flags: Confusing SG and NACL; not allowing ephemeral ports in NACL inbound; relying only on NACLs for security.
Q213: IAM Roles for EC2 — instance profiles
Level: Senior
Scenario: An EC2 instance needs to access S3. The team stores AWS credentials on the instance (in a config file). The credentials are exposed if the instance is compromised.
Impact: Credential exposure. Unauthorized AWS access. Security violation.
Root Cause: Storing long-term credentials on the instance instead of using an IAM role.
Simple explanation: You write the safe combination on a sticky note attached to the safe. Anyone who sees it can open the safe.
Technical Answer:
- Use IAM Roles for EC2 (instance profile) — temporary credentials provided via instance metadata service (IMDS).
- Attach the IAM role at launch or attach to a running instance.
- Applications use the AWS SDK which automatically retrieves temporary credentials from IMDS.
- Rotate credentials automatically (IMDS handles rotation, short-lived credentials).
- Use IMDSv2 (session token required) to prevent SSRF attacks.
Code/Syntax Justification:
# No credentials needed in code — SDK uses IMDS automatically
import boto3
s3 = boto3.client('s3')
s3.list_buckets() # Uses instance role credentials automatically
Workflow Diagram:
Stored credentials: IAM Role for EC2:
Credentials on instance Instance profile attached
| |
v v
Credential exposure Temporary credentials via IMDS
🔍 Behind the Question: IAM Roles for EC2, instance profiles, IMDS, temporary credentials, least privilege.
❌ The Red Flags: Storing access keys on EC2; not using IAM roles; IMDSv1 (no session token).
Q214: EBS volumes — types and selection
Level: Senior
Scenario: A team runs a high-performance database on EC2 with gp2 EBS volumes. The database is slow under write load. IOPS are exhausted.
Impact: Database latency. Application timeouts. Poor performance.
Root Cause: gp2 IOPS are tied to volume size (3 IOPS per GB, max 16,000). Small volumes have low baseline IOPS.
Simple explanation: A water pipe is too narrow. Water flows slowly. You need a wider pipe.
Technical Answer:
- gp3: baseline 3,000 IOPS regardless of volume size, can provision up to 16,000 IOPS separately. Better price/performance.
- io2: up to 64,000 IOPS, sub-millisecond latency, for critical databases. Higher cost.
- io2 Block Express: up to 256,000 IOPS, sub-millisecond latency, for mission-critical databases.
- st1/sc1: throughput-optimized HDD for large sequential workloads (big data, data warehouses).
- Magnetic: legacy, avoid.
Code/Syntax Justification:
# gp3 with provisioned IOPS
ec2.create_volume(
VolumeType='gp3',
Size=100,
Iops=3000,
Throughput=125,
Encrypted=True
)
Workflow Diagram:
gp2: gp3:
IOPS tied to size (3 per GB) 3,000 IOPS baseline regardless of size
| |
v v
Small volume = low IOPS Can provision IOPS independently
Database slow Database fast
🔍 Behind the Question: EBS volume types, IOPS, throughput, gp3 vs io2, volume selection.
❌ The Red Flags: gp2 for high-performance databases; not provisioning IOPS independently; not using io2 for critical databases.
Q215: EBS snapshots — backup and point-in-time recovery
Level: Senior
Scenario: A production EBS volume is accidentally deleted. The team has daily snapshots but the last one is 24 hours old. They lose 24 hours of data.
Impact: Data loss (24 hours). Recovery incomplete.
Root Cause: Backup frequency (daily snapshots) doesn't meet Recovery Point Objective (RPO).
Simple explanation: You back up your files every night at midnight. You delete a file at 2 PM. The last backup is from midnight. You lost 14 hours of work.
Technical Answer:
- Schedule EBS snapshots more frequently (every 4-6 hours) for critical volumes.
- Use Amazon Data Lifecycle Manager (DLM) to automate snapshot creation and retention.
- Cross-region snapshot copy for disaster recovery.
- Test snapshot restore regularly — backup is useless without verified restore.
- Use EBS Multi-Attach or EBS Direct APIs for advanced patterns.
Code/Syntax Justification:
# Create EBS snapshot
ec2.create_snapshot(
VolumeId='vol-1234567890abcdef0',
Description='Production DB snapshot'
)
Workflow Diagram:
Daily snapshots: Frequent snapshots (DLM):
Snapshot at midnight Snapshots every 4 hours
| |
v v
Data deleted at 2 PM Data deleted at 2 PM
| |
v v
Restore to midnight (lose 24h) Restore to 12 PM (lose 2h)
24 hours data loss 2 hours data loss
🔍 Behind the Question: EBS snapshots, DLM, RPO, backup frequency, disaster recovery.
❌ The Red Flags: Daily snapshots only; no DLM automation; not testing restores; no cross-region copy.
Q216: EBS encryption — data at rest
Level: Senior
Scenario: A team stores sensitive customer data on EBS volumes without encryption. The disk is physically accessed (disk theft or improper disposal). Data is readable.
Impact: Data breach. Compliance violation (GDPR, HIPAA, PCI-DSS).
Root Cause: EBS volumes not encrypted at rest. Data stored in plaintext on physical disk.
Simple explanation: You store sensitive documents in an unlocked safe. Anyone who opens the safe can read them.
Technical Answer:
- Enable EBS encryption at volume creation (EBS encryption uses KMS keys).
- Use default encryption for all new EBS volumes in the account.
- Encrypt snapshots too (snapshots inherit encryption from source volume).
- Use customer-managed KMS keys (CMK) for key rotation and audit.
- Encryption has minimal performance impact (AWS Nitro handles it efficiently).
Code/Syntax Justification:
# Encrypted EBS volume
ec2.create_volume(
VolumeType='gp3',
Size=100,
Encrypted=True,
KmsKeyId='arn:aws:kms:...:key/...'
)
Workflow Diagram:
Unencrypted EBS: Encrypted EBS:
Data in plaintext on disk Data encrypted at rest
| |
v v
Disk theft = data breach Disk theft = unreadable data
🔍 Behind the Question: EBS encryption, KMS keys, snapshot encryption, default encryption, compliance.
❌ The Red Flags: Unencrypted EBS volumes; not encrypting snapshots; using AWS-managed keys when CMK needed.
Q217(b): EBS vs instance store — persistence choice
Level: Senior
Scenario: A team runs a database on EC2 with instance store (ephemeral) storage. The instance is stopped/restarted. All data is lost.
Impact: Data loss. Database unavailable. Recovery from backup needed.
Root Cause: Instance store is tied to the host. Data lost when instance is stopped, terminated, or host fails.
Simple explanation: Instance store is like scratch paper — disappears when thrown away. EBS is like a notebook — persists.
Technical Answer:
- Use EBS volumes for data that must persist (databases, user files, application state).
- Use instance store only for temporary data (cache, temp files, load balancer buffers).
- Enable EBS encryption for sensitive data.
- Use EBS snapshots for backup.
- For databases, consider RDS (managed) instead of self-managed EC2 + EBS.
Code/Syntax Justification:
# Instance store (ephemeral) — specified in block device mapping at launch
# EBS volume — separate create_volume call, attach to instance
ec2.attach_volume(
VolumeId='vol-1234567890abcdef0',
InstanceId='i-1234567890abcdef0',
Device='/dev/sdf'
)
Workflow Diagram:
Instance store: EBS volume:
Data lost on stop/terminate Data persists across stop/start
| |
v v
Database data lost Database data intact
🔍 Behind the Question: Instance store vs EBS, persistence, stop/start behavior, EBS encryption.
❌ The Red Flags: Database on instance store; no EBS encryption; no EBS snapshots.
Q218: AMI — golden image and fast provisioning
Level: Senior
Scenario: A team launches EC2 instances from a base AMI and runs user-data scripts to install dependencies. Each launch takes 20 minutes. Auto scaling is slow.
Impact: Slow auto-scaling. Instances not ready during traffic spikes.
Root Cause: User-data scripts run at launch time. Long bootstrapping.
Simple explanation: You bake a cake from scratch every time. You should bake ahead (golden AMI) and just frost when needed.
Technical Answer:
- Create golden AMI with dependencies, security patches, application pre-installed.
- Use EC2 Image Builder to automate AMI creation and testing.
- Launch from golden AMI — user-data only for environment-specific config.
- Reduces launch time from 20 minutes to 2-3 minutes.
- Enables faster auto-scaling and consistent configurations.
Code/Syntax Justification:
# Create AMI from running instance
ec2.create_image(
InstanceId='i-1234567890abcdef0',
Name='production-web-server-v1.2'
)
Workflow Diagram:
User-data bootstrap: Golden AMI:
Launch instance Launch from AMI
| |
v v
Run install scripts (20 min) Instance ready (2-3 min)
Application ready Application ready
Slow auto-scaling Fast auto-scaling
🔍 Behind the Question: AMI, golden image, EC2 Image Builder, launch time, auto-scaling speed.
❌ The Red Flags: No golden image; heavy user-data at launch; inconsistent configurations.
Q219: Launch Templates vs Launch Configurations
Level: Senior
Scenario: A team uses Launch Configurations (legacy) for Auto Scaling. They want to use a newer instance type (T3 instead of T2). Launch Configurations are immutable — must create new LC and update ASG.
Impact: Slow iteration. Can't easily update ASG configuration.
Root Cause: Launch Configurations are legacy and immutable. Launch Templates are versionable.
Simple explanation: A Launch Configuration is a printed form. To change one word, print a new form. A Launch Template is a Google Doc — versioned, editable.
Technical Answer:
- Use Launch Templates for new Auto Scaling groups.
- Launch Templates support versioning — create new version, update ASG to use specific version.
- Supports more features (T2/T3 CPU credits, EBS encryption, tagging, capacity rebalancing).
- Set default version in ASG; rollback by pointing to previous version.
- Migrate existing ASGs from LC to LT.
Code/Syntax Justification:
# Launch template
ec2.create_launch_template(
LaunchTemplateName='my-lt',
LaunchTemplateData={
'ImageId': 'ami-12345678',
'InstanceType': 'm6i.large',
'SecurityGroupIds': ['sg-12345678']
}
)
Workflow Diagram:
Launch Configuration: Launch Template:
Immutable Versioned (v1 -> v2 -> v3)
| |
v v
Change = create new LC Change = create new version
No rollback versioning Rollback = point to previous version
🔍 Behind the Question: Launch Template vs Launch Configuration, versioning, ASG updates, rollback.
❌ The Red Flags: Using Launch Configurations (legacy); no versioning; can't rollback easily.
Q220: Auto Scaling Group — scaling policies
Level: Senior
Scenario: An ASG uses simple scaling (add 2 instances when CPU > 70%). During traffic spikes, it adds instances too slowly or too many. The group oscillates.
Impact: Poor scaling response. Cost waste or performance issues.
Root Cause: Simple scaling policies don't adapt to rate of change. Target tracking maintains a specific metric value more smoothly.
Simple explanation: You adjust shower temperature by fixed amounts. You overshoot (too hot) then undershoot (too cold). Target tracking sets a target temperature and adjusts smoothly.
Technical Answer:
- Use target tracking scaling policies (e.g., keep CPU at 50%). ASG adds/removes instances to maintain target.
- Use step scaling for predictable metric ranges (add 2 instances at 70%, add 4 at 80%).
- Use scheduled scaling for predictable patterns (business hours).
- Set cooldown periods appropriately to avoid thrashing.
- Monitor CPUUtilization and GroupInServiceInstances.
Code/Syntax Justification:
# Target tracking scaling policy
applicationautoscaling.put_scaling_policy(
PolicyName='cpu-target-tracking',
ServiceNamespace='ec2',
ResourceId='autoScalingGroup/my-asg',
ScalableDimension='autoscaling:autoScalingGroup:DesiredCapacity',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'PredefinedMetricSpecification': {'PredefinedMetricType': 'ASGAverageCPUUtilization'},
'TargetValue': 50.0
}
)
Workflow Diagram:
Simple scaling: Target tracking:
CPU > 70% -> add 2 instances Target: CPU = 50%
| |
v v
CPU > 70% again -> add 2 more CPU rises -> add instances
Oscillates Smoothly maintains 50%
🔍 Behind the Question: ASG scaling policies, target tracking vs step scaling, cooldown, oscillation.
❌ The Red Flags: Simple scaling only; no cooldown; not using target tracking for CPU-based scaling.
Q221(b): Auto Scaling — cooldown periods
Level: Senior
Scenario: An ASG scales out rapidly during a traffic spike. New instances are still booting when the ASG adds more. The group overshoots (too many instances). Then scales in too aggressively. Oscillation.
Impact: Cost waste. Performance issues. Instance thrashing.
Root Cause: No cooldown period. ASG doesn't wait for new instances to become healthy before scaling again.
Simple explanation: You turn up the shower temperature. Before the water warms up, you turn it up again. Now it's scalding. You turn it down. Now it's freezing.
Technical Answer:
- Set default cooldown (time after scaling activity before another can start).
- New instances need time to boot and pass health checks.
- Cooldown prevents rapid successive scaling actions.
- Different cooldowns for scale-out vs scale-in can be set.
Code/Syntax Justification:
# Auto Scaling group with cooldown
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='my-asg',
MinSize=2,
MaxSize=10,
DesiredCapacity=2,
DefaultCooldown=300 # 5 minutes
)
Workflow Diagram:
No cooldown: With cooldown:
Scale out -> new instance Scale out -> wait 5 min
| |
v v
Scale out again immediately New instance healthy -> can scale again
Oscillation Stable scaling
🔍 Behind the Question: ASG cooldown, scaling oscillations, health checks, default cooldown.
❌ The Red Flags: No cooldown or too short cooldown; rapid successive scaling actions.
Q222: Spot Instances — interruption handling
Level: Senior
Scenario: A batch processing job runs on Spot Instances to save 90% cost. AWS sends a 2-minute interruption warning. The application doesn't handle it. Instances are terminated mid-job.
Impact: Lost work. Incomplete batches. Jobs restart from scratch.
Root Cause: Application doesn't monitor Spot interruption notices. No checkpointing.
Simple explanation: You're building a sandcastle. The tide is coming in (2-minute warning). You don't leave. The wave washes away your castle.
Technical Answer:
- Monitor Spot Instance interruption notice (IMDS metadata).
- Poll every 5 seconds; when action=terminate with 2-minute timeout, start graceful shutdown.
- Checkpoint progress to durable storage (S3, EBS).
- Use Spot Fleet with diversification across instance types and AZs.
- Design jobs to be idempotent and resumable from checkpoints.
Code/Syntax Justification:
# Check Spot interruption notice
import requests
resp = requests.get('http://169.254.169.254/latest/meta-data/spot/instance-action', timeout=1)
if resp.status_code == 200:
# Instance will be terminated in 2 minutes
checkpoint_and_shutdown()
Workflow Diagram:
Spot instance running job: Spot instance with interruption handling:
Running Running
| |
v v
2-minute interruption warning 2-minute interruption warning
| |
v v
Instance terminated immediately Checkpoint to S3 -> graceful shutdown
Job restarts from scratch Job resumes from checkpoint
🔍 Behind the Question: Spot interruption handling, IMDS metadata, checkpointing, Spot Fleet diversification.
❌ The Red Flags: Not monitoring interruption notices; no checkpointing; single instance type/AZ.
Q223: Spot Fleet — diversification and allocation strategy
Level: Principal
Scenario: A team runs Spot Instances of one type (m5.large) in one AZ. AWS interrupts all of them simultaneously. The job fails. No diversification.
Impact: Job failure. Lost compute capacity.
Root Cause: No diversification across instance types and AZs. Single point of failure.
Simple explanation: You rent all warehouse space in one building. The building closes. You have nowhere to store goods.
Technical Answer:
- Use Spot Fleet with diversification across multiple instance types and AZs.
- Set allocation strategy: capacity-optimized (lowest interruption risk) or lowest-price.
- Handle interruption notices (2-minute warning) via IMDS.
- Checkpoint work to durable storage (S3).
- Use capacity-optimized-prioritized to define preferred instance types.
Code/Syntax Justification:
# Spot Fleet with diversification
ec2.request_spot_fleet(
SpotFleetRequestConfig={
'AllocationStrategy': 'capacity-optimized',
'TargetCapacity': 100,
'LaunchSpecifications': [
{'InstanceType': 'm5.large', 'AvailabilityZone': 'us-east-1a'},
{'InstanceType': 'm5.xlarge', 'AvailabilityZone': 'us-east-1b'},
{'InstanceType': 'c5.large', 'AvailabilityZone': 'us-east-1c'}
]
}
)
Workflow Diagram:
No diversification: Spot Fleet diversification:
All instances: m5.large in 1AZ Instance types: m5.large, m5.xlarge, c5.large
| |
v v
AWS interrupts m5.large capacity AWS interrupts one type/AZ
All compute lost Other instances continue
Job fails Job continues (reduced capacity)
🔍 Behind the Question: Spot Fleet, diversification, instance types, AZs, interruption handling.
❌ The Red Flags: One instance type in one AZ; no diversification; no interruption handling.
Q224: Placement groups — cluster, spread, partition
Level: Senior
Scenario: A team runs HPC workloads. Instances scattered across AZs. Network latency between nodes is high. MPI jobs are slow.
Impact: Poor application performance. High inter-node latency.
Root Cause: No placement strategy. Instances launched without placement group.
Simple explanation: Team members in different buildings. They spend all day walking between buildings to talk. They should be in the same room.
Technical Answer:
- Use cluster placement group for low-latency, high-throughput inter-node communication (same AZ, same rack).
- Use spread placement group for critical instances that must be isolated (different racks).
- Use partition placement group for large distributed workloads (HDFS, Cassandra, Kafka).
- Choose based on workload: HPC (cluster), critical isolation (spread), distributed storage (partition).
- Placement groups work with specific instance types.
Code/Syntax Justification:
# Create cluster placement group
ec2.create_placement_group(
GroupName='hpc-cluster',
Strategy='cluster'
)
# Launch into placement group
ec2.run_instances(
Placement={'GroupName': 'hpc-cluster'},
InstanceType='c5n.18xlarge',
MinCount=10,
MaxCount=10
)
Workflow Diagram:
No placement group: Cluster placement group:
Instances scattered across AZs Instances in same AZ, same rack
| |
v v
High inter-node latency Low-latency, high-throughput
MPI jobs slow MPI jobs fast
🔍 Behind the Question: Placement groups, cluster/spread/partition, inter-node latency, enhanced networking.
❌ The Red Flags: No placement group for HPC; spread placement for HPC (wrong strategy); incompatible instance types.
Q225: Enhanced Networking (ENA, EFA)
Level: Senior
Scenario: A team runs MPI/ML workloads on EC2. Network throughput between instances is low. CPU is underutilized because nodes wait for network data.
Impact: Poor application performance. Network-bound.
Root Cause: Instances don't use Enhanced Networking (ENA or EFA).
Simple explanation: Moving water through a garden hose. You need a fire hose. Standard networking is the garden hose; ENA/EFA is the fire hose.
Technical Answer:
- Use Enhanced Networking (ENA) for improved throughput and lower latency (most modern instance types).
- Use Elastic Fabric Adapter (EFA) for HPC/ML workloads requiring OS-bypass, low-latency, high-throughput inter-node communication (MPI).
- Choose instance types with enhanced networking (c5n, p4d, etc.).
- Enable EFA at launch.
- Measure with iperf3 between instances.
Code/Syntax Justification:
# Launch with EFA
ec2.run_instances(
ImageId='ami-12345678',
InstanceType='p4d.24xlarge',
MinCount=8,
MaxCount=8,
Options={'Efa': {'Enabled': True}},
Placement={'GroupName': 'mpi-cluster'}
)
Workflow Diagram:
Standard networking: ENA/EFA:
Virtualized network OS-bypass, low latency
| |
v v
Lower throughput, higher latency High throughput, low latency
Application network-bound Application compute-bound (optimal)
🔍 Behind the Question: Enhanced Networking, ENA, EFA, MPI, OS-bypass, network performance.
❌ The Red Flags: Standard networking for HPC/ML; no EFA for MPI; not measuring network throughput.
Q226: T2/T3/T3a burstable instances — CPU credits
Level: Senior
Scenario: A dev server on T3 instances runs out of CPU credits. The instance is limited to baseline performance. Application slow.
Impact: Application slow. Unpredictable performance.
Root Cause: T2/T3/T3a are burstable instances. CPU credits accumulate when idle, spent when busy. Once exhausted, performance drops to baseline.
Simple explanation: You have a prepaid phone card. You use all minutes. Calls are now limited to a slow rate.
Technical Answer:
- Monitor CPU credit balance (CPUCreditBalance CloudWatch metric).
- Understand baseline performance (percentage of one vCPU).
- Use T3 Unlimited mode to allow bursting beyond credits (pays for excess).
- For consistent workloads, use M-series instead of burstable instances.
- Right-size based on actual CPU utilization patterns.
Code/Syntax Justification:
# Launch T3 Unlimited
ec2.run_instances(
InstanceType='t3.medium',
MinCount=1,
MaxCount=1,
CreditSpecification={'CpuCredits': 'unlimited'}
)
Workflow Diagram:
T3 Standard: T3 Unlimited:
CPU credits exhausted CPU credits exhausted
| |
v v
Performance limited to baseline Can burst beyond credits (pay excess)
Application slow Application maintains performance
🔍 Behind the Question: Burstable instances, CPU credits, T3 Unlimited, baseline performance, right-sizing.
❌ The Red Flags: T3 for consistent high-CPU workloads; not monitoring CPU credits; not using Unlimited.
Q227: Dedicated Instances and Dedicated Hosts
Level: Principal
Scenario: A financial services company needs hardware dedicated to them (no sharing with other AWS customers). Standard EC2 instances run on shared hardware.
Impact: Compliance violation. Cannot pass audit.
Root Cause: Standard EC2 instances may share physical hardware with other AWS customers.
Simple explanation: You live in an apartment building (shared hardware). Compliance requires a single-family home (dedicated hardware).
Technical Answer:
- Use Dedicated Instances: run on hardware dedicated to a single AWS account.
- Use Dedicated Hosts: physical server fully dedicated; bring your own licenses (BYOL).
- Dedicated Hosts give visibility into sockets/cores and allow license cost optimization.
- Higher cost. Use only when compliance requires.
- Can combine with Auto Scaling (Dedicated Instances) or host placement affinity.
Code/Syntax Justification:
# Dedicated Instance
ec2.run_instances(
InstanceType='m5.large',
Placement={'Tenancy': 'dedicated'},
MinCount=1,
MaxCount=1
)
# Dedicated Host
response = ec2.allocate_hosts(
InstanceType='m5.large',
AvailabilityZone='us-east-1a',
Quantity=2
)
host_id = response['HostIds'][0]
# Launch onto Dedicated Host
ec2.run_instances(
InstanceType='m5.large',
Placement={'HostId': host_id, 'Tenancy': 'host'},
MinCount=1,
MaxCount=1
)
Workflow Diagram:
Standard EC2: Dedicated Instance/Host:
Hardware shared with other AWS Hardware dedicated to your account
customers |
| |
v v
Compliance violation Compliance satisfied
Cannot pass audit Pass audit, operate legally
🔍 Behind the Question: Dedicated Instances, Dedicated Hosts, compliance, BYOL, hardware isolation.
❌ The Red Flags: Standard EC2 for compliance workloads; not understanding Dedicated Host vs Instance.
Q228: EC2 hibernation
Level: Senior
Scenario: A team stops EC2 instances at night to save cost. Each morning, instances reboot and re-run initialization (10 minutes). Developers wait. In-memory state lost.
Impact: Wasted developer time. Slow startup. Lost state.
Root Cause: Stopping instances wipes RAM. Instance reboots from scratch.
Simple explanation: You turn off your computer without saving. When you turn it on, all apps closed. Reopen everything.
Technical Answer:
- Enable EC2 hibernation: saves RAM to EBS root volume on stop. Restores state on start.
- Instances start faster (no re-initialization). In-memory state preserved.
- Requirements: EBS root volume encrypted, instance size sufficient, supported AMI.
- Not suitable for workloads >16GB RAM or short-lived instances.
- Cost: pay for EBS storage of hibernated RAM + instance stopped (no compute charge).
Code/Syntax Justification:
# Enable hibernation on launch
ec2.run_instances(
ImageId='ami-12345678',
InstanceType='m5.large',
MaxCount=1,
MinCount=1,
HibernationOptions={'Configured': True},
BlockDeviceMappings=[{
'DeviceName': '/dev/sda1',
'Ebs': {'Encrypted': True, 'VolumeType': 'gp3'}
}]
)
Workflow Diagram:
Stop (no hibernation): Stop (hibernation):
RAM wiped to disk RAM saved to EBS (encrypted)
| |
v v
Start: re-initialize (10 min) Start: restore RAM (30 sec)
Developer waits Developer productive immediately
🔍 Behind the Question: EC2 hibernation, state preservation, EBS encryption requirement, cost trade-offs.
❌ The Red Flags: Hibernation on unencrypted EBS; hibernating >16GB RAM; hibernating short-lived instances.
Q229: IMDSv2 security
Level: Senior
Scenario: An application retrieves IAM role credentials from IMDS. A vulnerable web app allows SSRF. An attacker retrieves credentials from metadata endpoint.
Impact: Credential theft. Unauthorized AWS access. Lateral movement.
Root Cause: IMDSv1 allows unauthenticated GET requests. No session token required.
Simple explanation: Anyone in the building lobby can ask receptionist for master key. No ID check. IMDSv2 requires showing ID (session token).
Technical Answer:
- Use IMDSv2 (requires session token via PUT request, then GET with token header).
- Set HttpTokens to required (not optional) at launch.
- Set HttpPutResponseHopLimit to 1 (prevents container-to-container metadata access).
- Use IAM roles for EC2 (not stored credentials).
- Rotate credentials automatically (IMDS handles rotation).
Code/Syntax Justification:
# IMDSv2: get session token first
import requests
token_response = requests.put(
'http://169.254.169.254/latest/api/token',
headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'},
timeout=2
)
token = token_response.text
creds_response = requests.get(
'http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name',
headers={'X-aws-ec2-metadata-token': token},
timeout=2
)
Workflow Diagram:
IMDSv1 (insecure): IMDSv2 (secure):
GET metadata PUT /api/token -> get token
| |
v v
Credentials returned GET metadata + token header
No authentication Token validated, credentials returned
SSRF attack succeeds SSRF attack blocked (no token)
🔍 Behind the Question: IMDSv1 vs IMDSv2, SSRF protection, session tokens, HttpTokens required.
❌ The Red Flags: IMDSv1 (HttpTokens optional); no session token; HttpPutResponseHopLimit not set.
Q230: EC2 monitoring — CloudWatch
Level: Senior
Scenario: A team has basic EC2 monitoring (5-minute intervals). During an incident, CPU spikes for 2 minutes between data points. They miss the spike.
Impact: Missed incidents. Slow MTTDR.
Root Cause: Basic monitoring is 5-minute intervals. Detailed monitoring is 1-minute intervals.
Simple explanation: You check your security camera every 5 minutes. A burglar enters and leaves in 2 minutes. You don't see them.
Technical Answer:
- Enable detailed monitoring (1-minute intervals) for critical workloads.
- Basic monitoring is free; detailed monitoring costs extra per instance per month.
- Use CloudWatch metrics: CPUUtilization, NetworkIn/Out, DiskReadOps/WriteOps, StatusCheckFailed.
- Create CloudWatch alarms on detailed metrics for faster detection.
- Combine with CloudWatch Logs for application-level visibility.
Code/Syntax Justification:
# Enable detailed monitoring
ec2.monitor_instances(InstanceIds=['i-1234567890abcdef0'])
# CloudWatch alarm on CPU
cloudwatch.put_metric_alarm(
AlarmName='HighCPU',
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistic='Average',
Period=60,
Threshold=80,
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=3
)
Workflow Diagram:
Basic monitoring (5 min): Detailed monitoring (1 min):
CPU spike at 10:02, ends 10:04 CPU spike at 10:02, ends 10:04
| |
v v
Data points at 10:00, 10:05 Data points at 10:02, 10:03, 10:04
Misses the spike Catches the spike
🔍 Behind the Question: EC2 detailed monitoring, CloudWatch metrics, monitoring intervals, alarms.
❌ The Red Flags: Basic monitoring for critical workloads; no CloudWatch alarms; not understanding 5-min vs 1-min.
Q231: EC2 status checks — system vs instance
Level: Senior
Scenario: An EC2 instance shows Status Check Failed. The team doesn't know if it's the host (system check) or instance OS (instance check). They reboot when they should stop/start.
Impact: Wrong remediation action. Longer downtime.
Root Cause: Not understanding difference between system status checks (host) and instance status checks (OS/application).
Simple explanation: A car won't start. Is it the engine (system) or the key (instance)? You need to know which to fix.
Technical Answer:
- System status check: detects issues with underlying host (hardware, network, AWS side). Fix: stop/start instance (moves to new host).
- Instance status check: detects issues with instance itself (OS, application, misconfiguration). Fix: reboot or troubleshoot instance.
- Both checks must pass for instance healthy.
- Use EC2 Auto Scaling health checks to replace instances failing status checks.
- Monitor StatusCheckFailed, StatusCheckFailed_Instance, StatusCheckFailed_System.
Code/Syntax Justification:
# Check status checks
response = ec2.describe_instance_status(InstanceIds=['i-1234567890abcdef0'])
for status in response['InstanceStatuses']:
print(status['InstanceState']['Name'])
print(status['SystemStatus']['Status'])
print(status['InstanceStatus']['Status'])
Workflow Diagram:
Status Check Failed:
|
+-- System Status Check failed -> AWS host issue -> stop/start (new host)
|
+-- Instance Status Check failed -> OS/application issue -> reboot/troubleshoot
🔍 Behind the Question: Status checks, system vs instance, remediation actions, CloudWatch metrics.
❌ The Red Flags: Rebooting for system check failures; stop/start for instance check failures; not distinguishing check types.
Q232: EC2 Capacity Reservations
Level: Principal
Scenario: A team needs 100 instances during a product launch. On-Demand capacity unavailable in AZ. Instances fail to launch. Launch delayed.
Impact: Launch delay. Lost revenue. Poor customer experience.
Root Cause: No capacity reservation. On-Demand capacity is first-come-first-served.
Simple explanation: You go to a restaurant at peak hour. No tables available. You should have reserved a table.
Technical Answer:
- Use Capacity Reservations to reserve EC2 capacity in specific AZ.
- Reservations ensure capacity available when needed.
- Can be shared across accounts (Capacity Reservation groups).
- Combine with Auto Scaling (capacity-rebalanced) for Spot + On-Demand mix.
- Pay for reserved capacity even if not used.
Code/Syntax Justification:
# Create Capacity Reservation
ec2.create_capacity_reservation(
InstanceType='m6i.large',
InstancePlatform='Linux/UNIX',
AvailabilityZone='us-east-1a',
InstanceCount=100
)
# Run instances into Capacity Reservation
ec2.run_instances(
InstanceType='m6i.large',
MinCount=100,
MaxCount=100,
CapacityReservationSpecification={
'CapacityReservationPreference': 'open',
'CapacityReservationTarget': {
'CapacityReservationId': 'cr-1234567890abcdef0'
}
}
)
Workflow Diagram:
No Capacity Reservation: Capacity Reservation:
Launch 100 instances Reserve 100 instances in advance
| |
v v
Insufficient capacity Capacity guaranteed
Launch delayed Launch succeeds on time
🔍 Behind the Question: Capacity Reservations, guaranteed capacity, AZ capacity, launch planning.
❌ The Red Flags: No capacity reservation for critical launches; not understanding capacity scarcity.
Q233(b): EC2 Auto Scaling — target tracking vs step scaling
Level: Senior
Scenario: An ASG uses simple scaling (add 2 instances when CPU > 70%). During traffic spikes, adds instances too slowly or too many. Group oscillates.
Impact: Poor scaling response. Cost waste or performance issues.
Root Cause: Simple scaling policies don't adapt to rate of change.
Simple explanation: You adjust shower temperature by fixed amounts. You overshoot (too hot) then undershoot (too cold). Target tracking sets a target temperature and adjusts smoothly.
Technical Answer:
- Use target tracking scaling policies (e.g., keep CPU at 50%). ASG adds/removes instances to maintain target.
- Use step scaling for predictable metric ranges.
- Use scheduled scaling for predictable patterns (business hours).
- Set cooldown periods appropriately.
- Monitor CPUUtilization and GroupInServiceInstances.
Code/Syntax Justification:
# Target tracking scaling policy
applicationautoscaling.put_scaling_policy(
PolicyName='cpu-target-tracking',
ServiceNamespace='ec2',
ResourceId='autoScalingGroup/my-asg',
ScalableDimension='autoscaling:autoScalingGroup:DesiredCapacity',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'PredefinedMetricSpecification': {'PredefinedMetricType': 'ASGAverageCPUUtilization'},
'TargetValue': 50.0
}
)
Workflow Diagram:
Simple scaling: Target tracking:
CPU > 70% -> add 2 instances Target: CPU = 50%
| |
v v
CPU > 70% again -> add 2 more CPU rises -> add instances
Oscillates Smoothly maintains 50%
🔍 Behind the Question: ASG scaling policies, target tracking vs step scaling, cooldown, oscillation.
❌ The Red Flags: Simple scaling only; no cooldown; not using target tracking for CPU-based scaling.
Q234: EC2 Systems Manager (SSM) — Patch Manager
Level: Senior
Scenario: A team manages 50 EC2 instances. They manually log into each to apply security patches. Patching inconsistent. Some instances missing critical patches. Security audit fails.
Impact: Security vulnerabilities. Inconsistent patch state. Audit failure.
Root Cause: Manual patching. No automated patch management. No visibility into patch state.
Simple explanation: You update 50 apps on your phone one by one. You miss some. Phone vulnerable.
Technical Answer:
- Use EC2 Systems Manager (SSM) Patch Manager for automated patching.
- Create patch baselines (approved/rejected patches).
- Use maintenance windows to define patching schedules.
- Use SSM documents (automation) for consistent patching across instances.
- Monitor patch compliance via SSM compliance dashboard.
Code/Syntax Justification:
# SSM patch baseline
ssm.create_patch_baseline(
Name='Production-Baseline',
OperatingSystem='AMAZON_LINUX_2',
ApprovalRules={
'PatchRules': [{
'PatchFilterGroup': {
'PatchFilters': [
{'Key': 'CLASSIFICATION', 'Values': ['Security']},
{'Key': 'SEVERITY', 'Values': ['Critical', 'High']}
]
},
'ApproveAfterDays': 7
}]
}
)
Workflow Diagram:
Manual patching: SSM Patch Manager:
Log into each instance Patch baseline defines approved patches
| |
v v
Inconsistent patch state Maintenance window schedules patching
Security audit fails All instances compliant
🔍 Behind the Question: SSM Patch Manager, patch baselines, maintenance windows, compliance, automation.
❌ The Red Flags: Manual patching; no patch baseline; no maintenance windows; not monitoring compliance.
Q235: EC2 Systems Manager (SSM) — Session Manager
Level: Senior
Scenario: A team SSHs into EC2 instances with SSH keys. Keys are rotated infrequently. A compromised key grants access to all instances.
Impact: Credential exposure. Unauthorized instance access. Security violation.
Root Cause: SSH key-based access. No centralized access control or audit.
Simple explanation: You give every employee a master key. One lost key = all rooms accessible.
Technical Answer:
- Use SSM Session Manager for shell access without SSH keys.
- Session Manager uses IAM policies for access control.
- All sessions logged to CloudWatch Logs or S3 for audit.
- No bastion hosts needed. No open inbound SSH port (22).
- Use IAM policies to control who can start sessions to which instances.
Code/Syntax Justification:
# Start SSM session
ssm.start_session(
Target='i-1234567890abcdef0',
DocumentName='AWS-StartShellSession'
)
Workflow Diagram:
SSH key access: SSM Session Manager:
SSH key compromised IAM policy controls access
| |
v v
All instances accessible Session logged to CloudWatch
| |
v v
Security violation No SSH port open, no bastion host
🔍 Behind the Question: SSM Session Manager, SSH key elimination, session logging, bastion host elimination.
❌ The Red Flags: SSH key-based access; open port 22; no session logging; bastion hosts.
Q236: EC2 — Elastic IP vs Elastic Network Interface (ENI)
Level: Senior
Scenario: A team needs a static public IP for an EC2 instance. They assign an Elastic IP. The instance is stopped and started. The Elastic IP is disassociated.
Impact: IP address changes. Clients can't reach the instance.
Root Cause: Elastic IP is disassociated when instance is stopped. Not automatically re-associated on start.
Simple explanation: You give someone your phone number. You change your SIM card. They can't reach you anymore.
Technical Answer:
- Elastic IP is disassociated when instance is stopped. Must re-associate after start.
- For static IP that persists across stop/start, use Elastic IP and re-associate, or use a Network Load Balancer with static IP.
- ENI (Elastic Network Interface) can be detached from one instance and attached to another.
- ENI maintains private IP, public IP, security groups, MAC address.
- Use ENI for failover scenarios (move ENI from failed instance to standby).
Code/Syntax Justification:
# Associate Elastic IP
ec2.associate_address(
InstanceId='i-1234567890abcdef0',
AllocationId='eipalloc-1234567890abcdef0'
)
# Detach and attach ENI
ec2.detach_network_interface(NetworkInterfaceId='eni-1234567890abcdef0')
ec2.attach_network_interface(
DeviceIndex=1,
InstanceId='i-standby-1234567890abcdef0',
NetworkInterfaceId='eni-1234567890abcdef0'
)
Workflow Diagram:
Elastic IP on stopped instance: ENI failover:
EIP disassociated on stop ENI detached from failed instance
| |
v v
IP changes on start ENI attached to standby
Clients can't reach Standby takes over with same IP
🔍 Behind the Question: Elastic IP vs ENI, failover, static IP, network interface mobility.
❌ The Red Flags: Expecting EIP to persist across stop/start; not using ENI for failover.
Q237: EC2 — NAT Gateway vs NAT Instance
Level: Senior
Scenario: A team uses a NAT instance (EC2 running NAT software) for private subnet internet access. The NAT instance becomes a bottleneck and single point of failure.
Impact: Private subnet instances can't reach internet when NAT instance fails or is overloaded.
Root Cause: NAT instance is a single EC2 instance — single point of failure, limited throughput.
Simple explanation: One person routes all mail for a building. They get overwhelmed or sick. No mail gets out.
Technical Answer:
- Use NAT Gateway (managed, highly available) instead of NAT instance.
- NAT Gateway is managed by AWS — automatic failover within AZ.
- For cross-AZ high availability, deploy NAT Gateway in each AZ.
- NAT instance requires managing the EC2 instance (patching, scaling, HA).
- NAT Gateway charges hourly + data processing; NAT Instance charges for EC2 instance only.
Code/Syntax Justification:
# Create NAT Gateway
ec2.create_nat_gateway(
SubnetId='subnet-12345678',
AllocationId='eipalloc-1234567890abcdef0'
)
Workflow Diagram:
NAT Instance: NAT Gateway:
Single EC2 instance Managed, highly available
| |
v v
Single point of failure Automatic failover within AZ
Manual scaling Managed by AWS
🔍 Behind the Question: NAT Gateway vs NAT Instance, high availability, private subnet internet access.
❌ The Red Flags: Using NAT instance instead of NAT Gateway; single NAT Gateway for multi-AZ; not deploying NAT Gateway per AZ for HA.
Q238: EC2 — VPC Endpoints (Interface vs Gateway)
Level: Senior
Scenario: A team's EC2 instances in private subnets call S3. Traffic goes over the internet (via NAT Gateway). They want to keep traffic within AWS network.
Impact: Data egress charges. Traffic traverses public internet. Security concern.
Root Cause: No VPC Endpoint for S3. Traffic goes through NAT Gateway to public S3 endpoint.
Simple explanation: You send a letter to another city via the public postal service. You could use a private courier that stays within the building.
Technical Answer:
- Use VPC Endpoint (Gateway type) for S3 and DynamoDB — keeps traffic within AWS network, no data egress charges.
- Use VPC Endpoint (Interface type, powered by PrivateLink) for other services (SQS, SNS, KMS, CloudWatch, etc.).
- Interface endpoints use ENIs in your subnets with private IPs.
- Gateway endpoints use route table entries (no ENI).
- Both keep traffic off the public internet.
Code/Syntax Justification:
# Create VPC Endpoint for S3 (Gateway type)
ec2.create_vpc_endpoint(
VpcId='vpc-12345678',
ServiceName='com.amazonaws.us-east-1.s3',
VpcEndpointType='Gateway',
RouteTableIds=['rtb-12345678']
)
# Create VPC Endpoint for SQS (Interface type)
ec2.create_vpc_endpoint(
VpcId='vpc-12345678',
ServiceName='com.amazonaws.us-east-1.sqs',
VpcEndpointType='Interface',
SubnetIds=['subnet-12345678'],
SecurityGroupIds=['sg-12345678']
)
Workflow Diagram:
Without VPC Endpoint: With VPC Endpoint (Gateway for S3):
Private subnet -> NAT Gateway -> Private subnet -> VPC Endpoint -> S3
Internet -> S3 (stays within AWS network)
| |
v v
Data egress charges No data egress charges
Public internet traversal Private AWS network
🔍 Behind the Question: VPC Endpoints (Gateway vs Interface), PrivateLink, data egress, private connectivity.
❌ The Red Flags: No VPC Endpoints for S3/DynamoDB; traffic through NAT Gateway to public endpoints; not using Interface endpoints for other AWS services.
Q239: EC2 — Transit Gateway vs VPC Peering
Level: Principal
Scenario: A team has 10 VPCs that need to communicate. They use VPC peering (45 pairwise connections). Management is complex.
Impact: Complex mesh. Hard to manage. High operational overhead.
Root Cause: VPC peering is point-to-point. N VPCs need N(N-1)/2 connections.
Simple explanation: 10 people each need to talk to 9 others. 45 separate conversations. You should use a conference call (Transit Gateway) instead.
Technical Answer:
- Use Transit Gateway as a hub — attach all VPCs to one TGW. N VPCs need N attachments (not N² peering).
- VPC Peering: point-to-point, simple for 2 VPCs, doesn't scale.
- Transit Gateway: hub-and-spoke, transitive routing, centralized management.
- TGW supports inter-region peering too.
- Route tables control which VPCs can talk to which.
Code/Syntax Justification:
# Create Transit Gateway
ec2.create_transit_gateway(
Description='my-tgw'
)
# Attach VPC to Transit Gateway
ec2.create_transit_gateway_vpc_attachment(
TransitGatewayId='tgw-12345678',
VpcId='vpc-12345678',
SubnetIds=['subnet-12345678']
)
Workflow Diagram:
VPC Peering (mesh): Transit Gateway (hub-and-spoke):
VPC A <-> VPC B All VPCs -> Transit Gateway
VPC A <-> VPC C Transit Gateway -> all VPCs
VPC A <-> VPC D ... |
| |
v v
45 connections for 10 VPCs 10 attachments for 10 VPCs
Complex mesh Simple hub-and-spoke
🔍 Behind the Question: Transit Gateway vs VPC Peering, hub-and-spoke vs mesh, transitive routing, inter-region.
❌ The Red Flags: VPC peering mesh for many VPCs; not using Transit Gateway for centralized routing.
Q240: EC2 — Direct Connect vs VPN
Level: Principal
Scenario: A company needs a dedicated connection from their on-premises data center to AWS. They use VPN over the public internet. Latency is variable and security is a concern.
Impact: Variable latency. Public internet traversal. Not suitable for mission-critical workloads.
Root Cause: VPN uses public internet. No dedicated connection.
Simple explanation: You send data over the public highway. You should use a private dedicated line.
Technical Answer:
- Use AWS Direct Connect for dedicated network connection from on-premises to AWS.
- DX provides private connection, consistent latency, no public internet.
- VPN is faster to set up, cheaper, but uses public internet (variable latency).
- Use DX for mission-critical, high-bandwidth, consistent latency workloads.
- Can use VPN as backup for DX (failover).
Code/Syntax Justification:
# Create Direct Connect connection (CLI)
aws directconnect create-connection \
--location 'EqDC2' \
--connection-name 'my-dx-connection' \
--bandwidth '1Gbps'
Workflow Diagram:
VPN (public internet): Direct Connect (dedicated):
On-prem -> Internet -> AWS On-prem -> Direct Connect -> AWS
| |
v v
Variable latency Consistent low latency
Public internet Private AWS network
🔍 Behind the Question: Direct Connect vs VPN, dedicated connection, latency, hybrid connectivity.
❌ The Red Flags: Using VPN for mission-critical consistent latency; not using DX for high-bandwidth hybrid.
Q241: EC2 — AWS VPN (Site-to-Site)
Level: Senior
Scenario: A team needs to connect their on-premises data center to AWS quickly and cheaply. They set up AWS VPN.
Impact: Quick connectivity. Uses public internet.
Root Cause: VPN is fast to deploy but uses public internet.
Simple explanation: You set up a secure tunnel over the public highway. Fast to build, but shares the road with everyone else.
Technical Answer:
- AWS VPN (Site-to-Site) uses IPsec over public internet.
- Fast to deploy (minutes), low cost.
- Variable latency depending on internet conditions.
- Use for quick connectivity, backup for DX, or non-critical workloads.
- Two tunnels for redundancy (active/passive).
Code/Syntax Justification:
# Create VPN connection (CLI)
aws ec2 create-vpn-connection \
--type ipsec.1 \
--customer-gateway-id cgw-12345678 \
--vpn-gateway-id vgw-12345678
Workflow Diagram:
AWS VPN:
On-prem -> IPsec tunnel -> Public Internet -> AWS VPC
| |
v v
Fast to deploy Variable latency
Low cost Public internet traversal
🔍 Behind the Question: AWS VPN, Site-to-Site VPN, IPsec, public internet, hybrid connectivity.
❌ The Red Flags: Using VPN for consistent low-latency requirements; not configuring redundant tunnels.
Q242: EC2 — Bastion Host vs Session Manager
Level: Principal
Scenario: A team uses a bastion host (jump box) to access private EC2 instances. The bastion is a single point of failure and requires SSH key management.
Impact: Bastion compromise = access to all instances. SSH key management overhead.
Root Cause: Using bastion host instead of SSM Session Manager.
Simple explanation: You have one security guard at the front door. If they're compromised, everyone is at risk. You should use badge access instead.
Technical Answer:
- Use SSM Session Manager instead of bastion hosts.
- Session Manager uses IAM policies — no SSH keys, no open port 22.
- All sessions logged to CloudWatch Logs/S3.
- No bastion host to maintain, patch, or secure.
- Use IAM policies to control who can start sessions to which instances.
Code/Syntax Justification:
# Start SSM session instead of SSH
ssm.start_session(Target='i-1234567890abcdef0')
# vs SSH: ssh -i key.pem ec2-user@bastion-host, then ssh to private instance
Workflow Diagram:
Bastion Host: SSM Session Manager:
User -> Bastion -> Private Instance User -> SSM -> Private Instance
| |
v v
SSH keys, open port 22 IAM policies, no open port 22
| |
v v
Bastion compromise = all instances Session logged, no bastion to compromise
🔍 Behind the Question: Bastion Host vs Session Manager, SSH key elimination, IAM-based access, session logging.
❌ The Red Flags: Using bastion hosts; open port 22; SSH key management; no session logging.
Q243: EC2 — AWS Systems Manager Automation
Level: Senior
Scenario: A team manually performs common operational tasks (stop instance, create snapshot, replace instance). Each task is manual and error-prone.
Impact: Manual errors. Inconsistent operations. Slow incident response.
Root Cause: No automation for common operational tasks.
Simple explanation: You do everything by hand. You should use a script or robot.
Technical Answer:
- Use SSM Automation documents for common tasks (stop instance, create snapshot, replace instance, etc.).
- Automation documents are YAML/JSON-defined workflows.
- Can be triggered via Console, CLI, EventBridge, or CloudWatch Alarms.
- Built-in documents available (AWS-StartEC2Instance, AWS-CreateSnapshot, etc.).
- Create custom Automation documents for organization-specific tasks.
Code/Syntax Justification:
# Start SSM Automation
ssm.start_automation_execution(
DocumentName='AWS-StopEC2Instance',
Parameters={'InstanceId': ['i-1234567890abcdef0']}
)
Workflow Diagram:
Manual operations: SSM Automation:
Admin stops instance manually Automation document executes
| |
v v
Manual error possible Automated, consistent, auditable
| |
v v
Slow incident response Fast, consistent response
🔍 Behind the Question: SSM Automation, automation documents, operational automation, incident response.
❌ The Red Flags: Manual operational tasks; no automation documents; inconsistent operations.
Q244: EC2 — AWS Config
Level: Senior
Scenario: A team wants to track EC2 configuration changes over time. They don't know when an instance was modified or what changed.
Impact: No change history. Can't troubleshoot configuration drift. Compliance issues.
Root Cause: No configuration tracking.
Simple explanation: You don't keep records of changes. You don't know who changed what or when.
Technical Answer:
- Use AWS Config to record EC2 configuration changes.
- Config records configuration items (CIs) for EC2 instances, security groups, etc.
- Config Rules evaluate compliance against desired configurations.
- Use Config history to see what changed and when.
- Use Config remediation (SSM Automation) to auto-remediate non-compliant resources.
Code/Syntax Justification:
# Enable AWS Config for EC2
configservice.put_configuration_recorder(
ConfigurationRecorder={
'name': 'default',
'roleARN': 'arn:aws:iam::...:role/config-role',
'recordingGroup': {
'allSupported': True,
'includeGlobalResourceTypes': False
}
}
)
Workflow Diagram:
No config tracking: AWS Config:
No change history Records all EC2 changes
| |
v v
Can't troubleshoot drift See what changed, when, by whom
| |
v v
Compliance issues Compliance rules + auto-remediation
🔍 Behind the Question: AWS Config, configuration tracking, compliance rules, remediation, configuration drift.
❌ The Red Flags: No AWS Config; no change history; no compliance rules.
Q245: EC2 — CloudTrail
Level: Principal
Scenario: A team wants to know who terminated an EC2 instance. They have no audit trail of API calls.
Impact: No accountability. Can't investigate security incidents.
Root Cause: CloudTrail not enabled or not configured for EC2 events.
Simple explanation: You don't keep a log of who enters the building. You don't know who terminated the instance.
Technical Answer:
- Enable AWS CloudTrail to record all AWS API calls.
- CloudTrail logs EC2 API calls (RunInstances, TerminateInstances, etc.) with user identity.
- Store logs in S3 for long-term retention.
- Use CloudTrail Insights for unusual API activity detection.
- Integrate with CloudWatch Events/EventBridge for real-time alerts on sensitive API calls.
Code/Syntax Justification:
# Create CloudTrail trail
cloudtrail.create_trail(
Name='my-trail',
S3BucketName='my-cloudtrail-bucket',
IsMultiRegionTrail=True
)
Workflow Diagram:
No CloudTrail: CloudTrail:
No API call log All EC2 API calls logged
| |
v v
Don't know who terminated instance Know exactly who, when, from where
🔍 Behind the Question: CloudTrail, API call logging, audit trail, accountability, S3 storage.
❌ The Red Flags: No CloudTrail enabled; no S3 log storage; no Insights for anomaly detection.
Q246: EC2 — AWS Systems Manager Parameter Store
Level: Senior
Scenario: A team stores configuration (database connection strings, API keys) in EC2 instance environment variables or code. Values are hardcoded or in plaintext files.
Impact: Credential exposure. Configuration drift. Hard to update across instances.
Root Cause: No centralized parameter management.
Simple explanation: You write configuration on sticky notes on each computer. You want to change one value — you visit every computer.
Technical Answer:
- Use SSM Parameter Store for centralized configuration management.
- Store parameters as SecureString (encrypted with KMS) for secrets.
- Parameters have hierarchical paths (/prod/db/password, /prod/api/key).
- Lambda, EC2, ECS can retrieve parameters at runtime.
- Use parameter versions and policies (expiration, change notifications).
Code/Syntax Justification:
# Get parameter from Parameter Store
ssm = boto3.client('ssm')
response = ssm.get_parameter(
Name='/prod/db/password',
WithDecryption=True
)
password = response['Parameter']['Value']
Workflow Diagram:
Hardcoded config: Parameter Store:
Config in code/env vars Centralized parameter store
| |
v v
Hard to update across instances Update once, all instances read latest
Credential exposure Encrypted (SecureString) with KMS
🔍 Behind the Question: SSM Parameter Store, SecureString, KMS encryption, hierarchical parameters, configuration management.
❌ The Red Flags: Hardcoded credentials; plaintext config files; no centralized parameter management.
Q247: EC2 — AWS Systems Manager Documents (SSM Documents)
Level: Senior
Scenario: A team has custom operational procedures (patch instance, backup database, restart service). Each is run manually via SSH.
Impact: Manual errors. Inconsistent execution. No audit trail.
Root Cause: No automation documents for custom procedures.
Technical Answer:
- Create custom SSM Documents (Automation or Command documents) for custom procedures.
- SSM Documents are YAML/JSON-defined workflows.
- Can be executed via Console, CLI, EventBridge, or State Manager associations.
- State Manager ensures consistent state (e.g., ensure agent running, ensure patch baseline applied).
- Documents support parameters, outputs, and error handling.
Code/Syntax Justification:
# SSM Command document example
ssm.send_command(
InstanceIds=['i-1234567890abcdef0'],
DocumentName='AWS-RunShellScript',
Parameters={'commands': ['yum update -y']}
)
Workflow Diagram:
Manual SSH procedures: SSM Documents:
Admin logs in, runs commands SSM Document executes consistently
| |
v v
Manual errors Automated, auditable, consistent
| |
v v
No audit trail Execution logged, results captured
🔍 Behind the Question: SSM Documents, Command documents, Automation documents, State Manager.
❌ The Red Flags: Manual SSH procedures; no automation documents; inconsistent execution.
Q248: EC2 — AWS Config Rules
Level: Principal
Scenario: A team wants to ensure all EC2 instances have specific tags (Environment, Owner, CostCenter). They don't have a way to enforce this.
Impact: Untagged instances. Cost allocation issues. Untracked resources.
Root Cause: No rule enforcement for resource tags.
Technical Answer:
- Use AWS Config Rules to evaluate EC2 instance tag compliance.
- Config Rules can be AWS-managed or custom (Lambda-based).
- Rules trigger on configuration changes (e.g., new instance launched).
- Non-compliant resources flagged in Config dashboard.
- Can auto-remediate with SSM Automation (add missing tags).
Code/Syntax Justification:
# Put Config Rule for required tags
configservice.put_config_rule(
ConfigRule={
'ConfigRuleName': 'required-tags',
'Description': 'EC2 instances must have required tags',
'Source': {
'Owner': 'AWS',
'SourceIdentifier': 'REQUIRED_TAGS'
},
'Scope': {
'ComplianceResourceTypes': ['AWS::EC2::Instance']
}
}
)
Workflow Diagram:
No tag enforcement: AWS Config Rules:
Instances launched without tags Rule checks tags on launch
| |
v v
Untracked costs Non-compliant flagged
| |
v v
Cost allocation issues Auto-remediate: add missing tags
🔍 Behind the Question: AWS Config Rules, tag compliance, auto-remediation, cost allocation.
❌ The Red Flags: No tag enforcement; untagged instances; no cost allocation tracking.
Q249: EC2 — AWS Organizations and SCPs
Level: Principal
Scenario: A company has multiple AWS accounts. They want to prevent any account from launching unencrypted EC2 instances or deleting CloudTrail trails.
Impact: Inconsistent security posture across accounts. Unencrypted instances. Deleted audit trails.
Root Cause: No centralized governance across accounts.
Simple explanation: You have multiple offices. Each does their own thing. No central policy enforcement.
Technical Answer:
- Use AWS Organizations to manage multiple accounts.
- Use Service Control Policies (SCPs) to set guardrails across accounts.
- SCPs restrict actions even for account administrators (they can't bypass SCPs).
- Example SCP: deny ec2:RunInstances unless encryption is enabled.
- SCPs applied at OU (Organizational Unit) level for hierarchical control.
Code/Syntax Justification:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RequireEncryptedEBS",
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "*",
"Condition": {
"Bool": {"ec2:Encrypted": "false"}
}
}
]
}
Workflow Diagram:
No SCPs: AWS Organizations + SCPs:
Each account independent Central guardrails across accounts
| |
v v
Unencrypted instances possible SCP blocks unencrypted instances
| |
v v
Inconsistent security Consistent security posture
🔍 Behind the Question: AWS Organizations, SCPs, multi-account governance, guardrails, OU structure.
❌ The Red Flags: No Organizations; no SCPs; account admins can bypass security; no centralized governance.
Q250: EC2 — AWS Control Tower
Level: Principal
Scenario: A company wants to set up a multi-account AWS environment with logging, security, and compliance baseline. They set up accounts manually.
Impact: Inconsistent setup. Missing security controls. Manual effort.
Root Cause: Manual account provisioning without standardized baseline.
Simple explanation: You build each house from scratch with different materials. You should use a blueprint (Control Tower).
Technical Answer:
- Use AWS Control Tower to set up and govern multi-account environment.
- Control Tower sets up landing zone (accounts, OUs, logging, security).
- Uses AWS Organizations, CloudTrail, Config, IAM Identity Center.
- Guardrails (preventive and detective) enforce security policies.
- Account factory for standardized account provisioning.
Code/Syntax Justification:
# Control Tower is primarily console/API-driven
# Landing zone setup via Control Tower console
# Account factory provisions new accounts via Service Catalog
Workflow Diagram:
Manual account setup: Control Tower Landing Zone:
Each account set up manually Standardized accounts, OUs, logging
| |
v v
Inconsistent security Guardrails enforced
| |
v v
Manual effort Automated, standardized
🔍 Behind the Question: AWS Control Tower, landing zone, account factory, guardrails, multi-account governance.
❌ The Red Flags: Manual account setup; no landing zone; no guardrails; inconsistent security.
Q251: EC2 — AWS Resource Access Manager (RAM)
Level: Senior
Scenario: A company has multiple AWS accounts. They want to share EC2 resources (subnets, License Manager configurations, Transit Gateways) across accounts without duplicating them.
Impact: Resource duplication. Higher cost. Inconsistent configuration.
Root Cause: No resource sharing across accounts.
Simple explanation: You buy a lawnmower for each house. You should share one lawnmower.
Technical Answer:
- Use AWS RAM to share resources across accounts.
- Share subnets (for multi-account VPC), Transit Gateways, License Manager configurations, etc.
- Sharing account owns the resource; consuming accounts use it.
- Resources appear in consuming account but are managed by sharing account.
- Reduces duplication and cost.
Code/Syntax Justification:
# Share a subnet with another account
ram.create_resource_share(
name='my-subnet-share',
resourceArns=['arn:aws:ec2:...:subnet/subnet-12345678'],
principals=['account-b-id']
)
Workflow Diagram:
No resource sharing: AWS RAM:
Each account has own subnets Sharing account shares subnets
| |
v v
Duplicate resources Shared resources
| |
v v
Higher cost Lower cost, consistent config
🔍 Behind the Question: AWS RAM, resource sharing, multi-account, subnet sharing, Transit Gateway sharing.
❌ The Red Flags: No resource sharing; duplicate resources across accounts; inconsistent configurations.
Q252: EC2 — AWS License Manager
Level: Senior
Scenario: A company runs Windows Server and SQL Server on EC2 with Bring-Your-Own-License (BYOL). They don't track license usage. They risk non-compliance.
Impact: License compliance violations. Audit failures. Unexpected costs.
Root Cause: No license tracking or management.
Simple explanation: You use software licenses but don't track how many you're using. You might be using more than you paid for.
Technical Answer:
- Use AWS License Manager to track and manage BYOL licenses.
- Create license configurations (license counting rules, allocation limits).
- Associate EC2 instances (Dedicated Hosts) with license configurations.
- License Manager enforces limits — blocks launches if licenses exhausted.
- Track usage, report on compliance, integrate with AWS Organizations.
Code/Syntax Justification:
# Create license configuration
license_manager.create_license_configuration(
Name='WindowsServer-2019',
LicenseCountingType='vCPU',
TotalLicenseCount=100
)
Workflow Diagram:
No license tracking: AWS License Manager:
Use licenses without tracking Track and enforce license usage
| |
v v
Compliance violations License compliance enforced
| |
v v
Audit failures Audit-ready reporting
🔍 Behind the Question: AWS License Manager, BYOL, license counting, compliance, Dedicated Hosts.
❌ The Red Flags: No license tracking; unmanaged BYOL; compliance violations; audit failures.