AWS EC2 Hands-On Interview Questions: CLI Commands, Launch Templates and Instance Troubleshooting (50 Questions)
This page has 50 hands-on EC2 interview questions with full answers. Most of them show a real AWS CLI command, sample output and what the output means. Interviewers for cloud and DevOps roles often say "show me how you would check that", and this page trains exactly that.
1. An everyday example: a car rental counter
Why do interviewers ask hands-on EC2 questions?
Anyone can say "EC2 is a virtual server". Hands-on questions show that you have really launched, changed and fixed instances. They also show that you can work fast from a terminal when the console is slow or not allowed.
Think of a car rental counter. A launch template is the booking form you fill once and reuse. The instance type is the car model. Stopping an instance is parking the car; terminating it is returning the car for good. The CLI is like phoning the counter directly instead of walking through the showroom.
How to use this page
- Use a test account and run only the read-only describe commands first.
- All IDs on this page are examples, such as account 111122223333 and instance i-0abc1234def567890.
- Stop or terminate anything you launch so it does not keep running.
2. Fresher level questions
Start here if you are a fresher or have less than two years of experience. Try to answer each question aloud first. Then open it and compare.
Q1. How do you list only running instances with their ID, type and private IP using the AWS CLI? Fresher
Use a filter for the state and a JMESPath query for the fields.
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query "Reservations[].Instances[].[InstanceId,InstanceType,PrivateIpAddress]" --output tableOutput:
---------------------------------------------------
| DescribeInstances |
+----------------------+-----------+--------------+
| i-0abc1234def567890 | t3.micro | 10.0.1.25 |
| i-0def5678abc123456 | m6i.large| 10.0.2.40 |
+----------------------+-----------+--------------+Two instances are running. The filter was applied by AWS, and the query picked three fields from each instance.
Tip: --output table is easy to read; use --output text when you pipe the result into a script.
Q2. How do you list the private IPs of all healthy instances behind an ALB target group? Fresher
First get target health, then look up the instances.
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:ap-south-1:111122223333:targetgroup/web-tg/0123456789abcdef --query "TargetHealthDescriptions[?TargetHealth.State=='healthy'].Target.Id" --output textOutput:
i-0abc1234def567890 i-0def5678abc123456aws ec2 describe-instances --instance-ids i-0abc1234def567890 i-0def5678abc123456 --query "Reservations[].Instances[].PrivateIpAddress" --output textOutput:
10.0.1.25 10.0.2.40Two targets are healthy, and these are their private IPs.
This is useful during incidents, to check logs on the exact servers that are taking traffic.
Q3. How do you find the instance ID of the EC2 instance you are logged in to? Fresher
Ask the instance metadata service. With IMDSv2 you first get a token.
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-idOutput:
i-0abc1234def567890This server is instance i-0abc1234def567890. Scripts use this to tag themselves, register in a service, or find their own settings.
You can also read placement/availability-zone and instance-type the same way.
Q4. What are the EC2 instance states, and which ones do you pay compute for? Fresher
- pending: the instance is starting.
- running: it is working. You pay for compute time.
- stopping and stopped: the instance is off. No compute charge, but you still pay for EBS volumes and any Elastic IP addresses.
- shutting-down and terminated: the instance is being deleted. Terminated instances stay visible for a short time, then disappear.
Check the state:
aws ec2 describe-instances --instance-ids i-0abc1234def567890 --query "Reservations[].Instances[].State.Name" --output textOutput:
stoppedThe instance is off but still exists, with its EBS root volume.
Q5. What is a launch template, and why is it better than typing settings every time? Fresher
A launch template saves launch settings: AMI, instance type, key pair, security groups, IAM instance profile, user data, tags and storage.
Why it helps:
- Every launch is the same, so fewer mistakes.
- It is versioned, so you can change settings and roll back.
- Auto Scaling groups, EC2 Fleet and the console all use it.
Launch from a template:
aws ec2 run-instances --launch-template LaunchTemplateName=web-lt,Version=3 --count 1AWS launched one instance with all the settings stored in version 3 of web-lt.
Q6. How do you change the instance type of an existing EC2 instance? Fresher
For an EBS-backed instance:
- Stop the instance.
- Change the type.
- Start it again.
aws ec2 stop-instances --instance-ids i-0abc1234def567890
aws ec2 modify-instance-attribute --instance-id i-0abc1234def567890 --instance-type "{\"Value\": \"m6i.large\"}"
aws ec2 start-instances --instance-ids i-0abc1234def567890Check first that the new type supports the same architecture (x86 or Arm), virtualisation, and drivers such as ENA and NVMe. Moving from x86 to a Graviton (Arm) type needs a new Arm AMI, not just a type change.
The public IP usually changes after a stop and start unless you use an Elastic IP.
Q7. What happens to the public IP address when you stop and start an instance? Fresher
An automatically assigned public IPv4 address is released when the instance stops. A new one is given when it starts.
The private IP address stays the same, because it belongs to the network interface in your subnet.
If you need a fixed public address, use an Elastic IP address, or better, put the instance behind a load balancer and use DNS.
Check the current address:
aws ec2 describe-instances --instance-ids i-0abc1234def567890 --query "Reservations[].Instances[].PublicIpAddress" --output textOutput:
203.0.113.48This is today's public IP. Do not hard-code it anywhere.
Q8. What does termination protection do, and how do you turn it on? Fresher
Termination protection stops anyone from terminating the instance through the console, CLI or API until the setting is turned off.
aws ec2 modify-instance-attribute --instance-id i-0abc1234def567890 --disable-api-terminationCheck it:
aws ec2 describe-instance-attribute --instance-id i-0abc1234def567890 --attribute disableApiTerminationOutput:
{"InstanceId": "i-0abc1234def567890", "DisableApiTermination": {"Value": true}}protection is on.
Notes: it does not stop a shutdown from inside the OS if the instance is set to terminate on shutdown, and Auto Scaling can still terminate instances it manages. There is also a separate stop protection setting.
Q9. How do you see why an instance failed its status checks from the CLI? Fresher
aws ec2 describe-instance-status --instance-ids i-0abc1234def567890 --include-all-instancesOutput:
"SystemStatus": {"Status": "ok"},
"InstanceStatus": {"Status": "impaired", "Details": [{"Name": "reachability", "Status": "failed"}]}The AWS host is fine (system status ok), but the operating system is not responding (instance status impaired). The problem is inside the instance: a boot error, a full disk, a bad network setting or a kernel problem.
Next steps: read the console output, take a console screenshot, or use the EC2 serial console.
Q10. How do you read the boot log of an instance without logging in? Fresher
Use get-console-output. It shows the system console log from boot.
aws ec2 get-console-output --instance-id i-0abc1234def567890 --latest --output textOutput:
[ 3.201234] EXT4-fs (nvme1n1): VFS: Can't find ext4 filesystem
[FAILED] Failed to mount /data.
You are in emergency mode.The instance is stuck in emergency mode because a disk listed in /etc/fstab could not be mounted.
Fix: detach the root volume, attach it to a rescue instance, correct fstab (use UUID and nofail), then reattach it.
Q11. What is an EC2 key pair, and what happens if you lose the private key? Fresher
A key pair is used for SSH login. AWS keeps the public key and puts it on the instance at first boot. You keep the private key file.
If you lose the private key:
- AWS cannot give it back.
- You can still get in with Session Manager (if the SSM agent and role are set up) or EC2 Instance Connect.
- Or stop the instance, attach its root volume to another instance, add a new public key to
~/.ssh/authorized_keys, and reattach the volume.
List key pairs:
aws ec2 describe-key-pairs --query "KeyPairs[].KeyName" --output textOutput:
shop-key admin-keyQ12. What are tags, and how do you add tags to an instance from the CLI? Fresher
Tags are key-value labels, such as Env=prod or Team=payments. They help you find resources, control access (ABAC) and split costs.
aws ec2 create-tags --resources i-0abc1234def567890 --tags Key=Env,Value=prod Key=Team,Value=paymentsCheck:
aws ec2 describe-tags --filters Name=resource-id,Values=i-0abc1234def567890 --output tableThe instance now carries both tags.
Best practice: add tags at launch in the launch template using tag specifications, so resources are never untagged even for a minute.
Q13. What is a placement group, and what are its three types? Fresher
A placement group controls how instances are placed on AWS hardware.
- Cluster: instances close together in one Availability Zone for very low latency and high network speed, such as HPC jobs.
- Spread: each instance on different hardware, to reduce the risk that one hardware failure stops several instances. There is a limit of seven running instances per AZ per group.
- Partition: instances grouped into partitions on separate racks, used by large distributed systems such as Kafka, HDFS and Cassandra.
aws ec2 create-placement-group --group-name hpc-pg --strategy clusterQ14. What is EC2 hibernation? Fresher
Hibernation saves the contents of memory (RAM) to the encrypted EBS root volume, then stops the instance. When you start it again, the memory is loaded back, so applications continue where they were.
Use case: applications that take a long time to warm up, such as loading large caches.
Requirements include: hibernation enabled at launch, an encrypted root volume big enough to hold RAM, and a supported instance family and OS.
aws ec2 stop-instances --instance-ids i-0abc1234def567890 --hibernateYou cannot turn hibernation on for an instance after launch.
Q15. How do you create an AMI from a running instance? Fresher
aws ec2 create-image --instance-id i-0abc1234def567890 --name "web-2026-11-20" --description "web server golden image"Output:
{"ImageId": "ami-0123456789abcdef0"}AWS started creating the AMI. It takes snapshots of the attached EBS volumes.
By default, AWS reboots the instance to get a consistent file system. You can use --no-reboot, but then files that are being written may be inconsistent.
Wait until it is ready:
aws ec2 wait image-available --image-ids ami-0123456789abcdef0Q16. How do you find the latest Amazon Linux 2023 AMI ID without hard-coding it? Fresher
AWS publishes current AMI IDs as public SSM parameters.
aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output textOutput:
ami-0a1b2c3d4e5f67890This is the latest AL2023 x86 AMI in your current Region. The ID is different in every Region.
In launch templates and CloudFormation, you can reference the parameter directly, so new launches always use the current image. For production, many teams pin a tested AMI and update it on purpose.
Q31. How do you see the details of an instance type, such as vCPUs, memory and network speed? Fresher
aws ec2 describe-instance-types --instance-types m6i.large --query "InstanceTypes[].[VCpuInfo.DefaultVCpus,MemoryInfo.SizeInMiB,NetworkInfo.NetworkPerformance]" --output textOutput:
2 8192 Up to 12.5 Gigabitm6i.large has 2 vCPUs, 8 GiB memory and network performance of up to 12.5 Gbps (burst).
"Up to" means the instance can burst to that speed but has a lower baseline. For steady high throughput, choose a bigger size.
3. Mid level questions
These questions check how you use the service in real projects. Interviewers expect the why, the how and one real example.
Q17. An Auto Scaling group keeps launching an old configuration after you updated the launch template. Why? Mid level
The group points to a specific launch template version.
- If the group uses version 3, a new version 4 is ignored.
- If it uses $Default, you must set version 4 as the default.
- If it uses $Latest, new launches use the newest version.
Check:
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names web-asg --query "AutoScalingGroups[].LaunchTemplate"Output:
[{"LaunchTemplateName": "web-lt", "Version": "3"}]The group is pinned to version 3.
Also, existing instances do not change. You need an instance refresh to replace them.
Q18. What is an instance refresh in Auto Scaling, and how do you start one safely? Mid level
An instance refresh replaces instances in batches with ones using the new launch template or AMI.
aws autoscaling start-instance-refresh --auto-scaling-group-name web-asg --preferences '{"MinHealthyPercentage": 90, "InstanceWarmup": 120}'Auto Scaling replaces instances so that at least 90% stay healthy, and waits 120 seconds for each new instance to warm up.
Safety options:
- Checkpoints that pause at a percentage so you can check metrics.
- Auto rollback if the refresh fails or an alarm goes off.
- Skip matching, so instances already on the desired config are not replaced.
Track progress with describe-instance-refreshes.
Q19. When would you add a warm pool to an Auto Scaling group, and what states can its instances be in? Mid level
A warm pool keeps pre-initialised instances ready next to the group, in a stopped, hibernated or running state.
When the group needs to scale out, it takes instances from the warm pool. They are ready much faster than brand new instances, because the slow setup (installing software, loading data) was done earlier.
Use when your application takes minutes to start.
aws autoscaling put-warm-pool --auto-scaling-group-name web-asg --pool-state Stopped --min-size 2Stopped instances in the pool avoid compute charges, but you still pay for their EBS volumes.
Q20. A T3 instance becomes very slow every afternoon, but CPU looks capped at a low level. What is happening? Mid level
T instances are burstable. They earn CPU credits when idle and spend them when busy. In standard mode, when credits run out, the CPU is limited to the baseline.
Check the credit balance:
aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUCreditBalance --dimensions Name=InstanceId,Value=i-0abc1234def567890 --start-time 2026-11-20T06:00:00Z --end-time 2026-11-20T12:00:00Z --period 3600 --statistics AverageOutput:
"Average": 0.0The instance has no credits left, so it runs at baseline speed.
Fix: switch to unlimited mode (extra usage is charged), or move to a non-burstable type such as M or C if the load is steady.
Q21. What is the Nitro System, and why does it matter in interviews? Mid level
Nitro is the modern EC2 platform. It moves networking, storage and security work onto dedicated hardware cards and uses a light hypervisor.
Why it matters:
- Almost all of the server's resources go to your instance, so performance is better.
- EBS volumes appear as NVMe devices (/dev/nvme1n1), not /dev/xvdf.
- Features such as the EC2 serial console, Nitro Enclaves and some newer instance types need Nitro.
- Higher network and EBS bandwidth.
Practical effect: scripts that expect /dev/xvdf break on Nitro instances, so mount disks by UUID.
Q22. How do you check if enhanced networking (ENA) is enabled on an instance? Mid level
aws ec2 describe-instances --instance-ids i-0abc1234def567890 --query "Reservations[].Instances[].EnaSupport"Output:
[true]Inside Linux:
ethtool -i ens5 | grep driverOutput:
driver: enaEnhanced networking with the ENA driver is on, so the instance gets higher bandwidth and lower latency.
If you move an old AMI to a newer instance type that requires ENA and the driver is missing, the instance may fail to start or have no network. Modern AMIs include ENA.
Q23. How do you copy an AMI to another Region, and what about encryption? Mid level
aws ec2 copy-image --source-region ap-south-1 --source-image-id ami-0123456789abcdef0 --region eu-west-1 --name "web-2026-11-20-dr" --encrypted --kms-key-id alias/dr-ebs-keyOutput:
{"ImageId": "ami-0fedcba9876543210"}A new AMI with a new ID is being created in eu-west-1. Its snapshots are encrypted with a key in the target Region.
Points:
- AMI IDs are different in each Region.
- KMS keys are Regional, so you choose a key in the destination Region.
- Copy AMIs as part of disaster recovery, and test launching from them.
Q24. How do you share an AMI with another AWS account? Mid level
aws ec2 modify-image-attribute --image-id ami-0123456789abcdef0 --launch-permission "Add=[{UserId=444455556666}]"account 444455556666 can now launch this AMI.
If the AMI's snapshots are encrypted:
- They must use a customer managed KMS key, not the AWS managed EBS key.
- The key policy must allow the other account to use the key (for example kms:Decrypt, kms:CreateGrant, kms:DescribeKey).
You can also share with an AWS Organization or OU instead of single accounts. The other account often copies the AMI into its own account so it does not depend on yours.
Q25. What is EC2 Image Builder, and why use it instead of manual AMIs? Mid level
EC2 Image Builder creates, tests and distributes AMIs (and container images) through a pipeline.
A pipeline has:
- A recipe: base image plus components, such as installing the CloudWatch agent and hardening steps.
- Tests that run on the new image.
- Distribution settings: which Regions and accounts get the AMI.
- A schedule, such as weekly, so images include the latest patches.
Why: golden images are repeatable, tested and patched without someone logging in to build them by hand.
Q26. An instance launch fails with "VcpuLimitExceeded". What does it mean and how do you fix it? Mid level
Your account has a vCPU quota per Region for each instance family group (for example, standard instances). The launch would go over it.
Check the quota with Service Quotas:
aws service-quotas get-service-quota --service-code ec2 --quota-code L-1216C47A --query "Quota.Value"Output:
32.0You can run up to 32 vCPUs of standard On-Demand instances in this Region.
Fix: stop unused instances, or request an increase in Service Quotas. Unlike capacity errors, waiting does not help.
Q27. How do you connect to an instance in a private subnet without a bastion host or public IP? Mid level
Two common options:
- Session Manager: the instance needs the SSM agent, an instance profile with AmazonSSMManagedInstanceCore, and a path to Systems Manager (NAT or VPC endpoints).
aws ssm start-session --target i-0abc1234def567890- EC2 Instance Connect Endpoint: you create an endpoint in the VPC, then connect over SSH through it.
aws ec2-instance-connect ssh --instance-id i-0abc1234def567890 --connection-type eiceBoth avoid opening SSH to the internet, and both can be controlled and logged with IAM and CloudTrail.
Q28. How do you replace the IAM role attached to a running instance? Mid level
An instance has one instance profile. You can replace it without stopping the instance.
aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0abc1234def567890 --query "IamInstanceProfileAssociations[].AssociationId" --output textOutput:
iip-assoc-0a1b2c3d4e5f67890aws ec2 replace-iam-instance-profile-association --association-id iip-assoc-0a1b2c3d4e5f67890 --iam-instance-profile Name=web-app-profileThe instance now uses the new profile. Applications pick up new credentials from the metadata service, usually within minutes, as SDKs refresh them.
Q29. What is the difference between Dedicated Instances and Dedicated Hosts? Mid level
- Dedicated Instances run on hardware used only by your account, but you do not control which physical server.
- Dedicated Hosts give you a whole physical server. You can see sockets and cores and place instances on that specific host.
Why Dedicated Hosts: software licences that are counted per socket or core (bring your own licence), and compliance rules that need a known physical server.
Most workloads do not need either. Normal shared tenancy is isolated by the Nitro hypervisor.
Q30. How do you find which instance types are available in a specific Availability Zone? Mid level
aws ec2 describe-instance-type-offerings --location-type availability-zone --filters Name=location,Values=ap-south-1a Name=instance-type,Values=m7g.* --query "InstanceTypeOfferings[].InstanceType" --output textOutput:
m7g.medium m7g.large m7g.xlarge m7g.2xlargeThese m7g sizes are offered in ap-south-1a.
Use this before you design a multi-AZ setup or a launch template, because not every type exists in every AZ. A type being offered does not mean capacity is always free at that moment.
Q32. How do you use user data with a launch template, and how do you check what user data an instance received? Mid level
User data goes into the launch template (base64 encoded by the CLI or console). To see what a running instance got:
aws ec2 describe-instance-attribute --instance-id i-0abc1234def567890 --attribute userData --query "UserData.Value" --output text | base64 -dOutput:
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginxThis is the script the instance ran at first boot.
Never put secrets in user data. Anyone with describe permission or access to the metadata service can read it. Fetch secrets from Secrets Manager at runtime instead.
Q33. What is an Auto Scaling lifecycle hook, and when do you use one? Mid level
A lifecycle hook pauses an instance during launch or termination so you can run custom actions.
Examples:
- On launch: install software or register with a configuration tool before the instance receives traffic.
- On termination: copy logs to S3 or drain jobs before the instance is removed.
aws autoscaling put-lifecycle-hook --lifecycle-hook-name drain-hook --auto-scaling-group-name web-asg --lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING --heartbeat-timeout 300When the work finishes, your script calls complete-lifecycle-action. If it does not, the default result applies after the timeout.
Q34. How do you find out why an Auto Scaling group terminated or launched instances? Mid level
aws autoscaling describe-scaling-activities --auto-scaling-group-name web-asg --max-items 3 --query "Activities[].[StartTime,StatusCode,Description,Cause]" --output textOutput:
2026-11-20T10:02:11Z Successful Terminating EC2 instance: i-0abc1234def567890 ...an instance was taken out of service in response to an ELB system health check failure.The instance was replaced because the load balancer health check failed, not because of scale-in.
Next step: check why the target was unhealthy (health check path, app errors, security groups), and whether the health check grace period is long enough.
Q35. How do you protect specific instances from being terminated during scale-in? Mid level
Use instance scale-in protection:
aws autoscaling set-instance-protection --instance-ids i-0abc1234def567890 --auto-scaling-group-name worker-asg --protected-from-scale-inscale-in will not choose this instance, but it can still be replaced if it becomes unhealthy.
Use case: workers processing a long job. The worker turns protection on when it starts a job and off when it finishes.
Do not leave every instance protected, or the group can never scale in.
4. Senior level and scenario questions
These questions check design thinking and troubleshooting. Think aloud. Say what you check first, what you change, and how you prevent it next time.
Q36. A new instance type migration from x86 to Graviton is planned for 200 instances. How do you do it safely? Senior
- Check software: OS, runtimes and agents must support Arm64. Interpreted languages (Python, Node.js, Java) usually work; native libraries and some containers need Arm builds.
- Build Arm AMIs or multi-architecture container images in the pipeline.
- Test performance and correctness in staging with real traffic patterns.
- Create a new launch template version with the Arm AMI and Graviton type.
- Roll out gradually: a mixed instances policy or one Auto Scaling group at a time, with instance refresh checkpoints and alarms.
- Keep the x86 version ready for rollback.
- Measure results: latency, errors and cost per request.
Q37. Instances in an Auto Scaling group keep getting replaced in a loop right after launch. How do you debug it? Senior
- Read scaling activities: are they replaced for EC2 health or ELB health?
- If ELB health: the app is not ready before health checks start. Increase the health check grace period, or fix the health check path.
- If EC2 health: check console output for boot failures.
- Check user data: did a package install fail? Read /var/log/cloud-init-output.log on an instance (suspend the replace process temporarily to keep one alive).
aws autoscaling suspend-processes --auto-scaling-group-name web-asg --scaling-processes ReplaceUnhealthy- Check the instance profile, security groups and subnet routes to dependencies.
Resume the process after you fix the problem.
Q38. How would you design EC2 capacity for a planned sale event where you cannot risk "InsufficientInstanceCapacity" errors? Senior
- Reserve capacity ahead with On-Demand Capacity Reservations in the AZs and types you need, for the event window.
- Use several instance types and AZs in the Auto Scaling group, so one sold-out type does not block scale-out.
- Pre-scale before the event with scheduled actions instead of waiting for alarms.
- Use warm pools so new instances are ready fast.
- Check vCPU quotas and other limits early.
- Load test at expected peak plus margin.
Release reservations after the event, because they are charged whether used or not.
Q39. How do you make a fleet of EC2 instances immutable instead of patching them in place? Senior
- Bake changes into a new AMI with Image Builder or a pipeline (OS patches, agents, application version).
- Update the launch template with the new AMI.
- Replace instances with an instance refresh or a blue/green Auto Scaling group swap.
- Never SSH in to change servers; block it or log it.
- Keep state off instances: data in RDS, S3, EFS or caches; sessions in a shared store.
Benefits: every server is identical, rollbacks are fast (use the old AMI), and drift disappears.
Patch Manager is still useful for long-lived instances that cannot be replaced easily.
Q40. An instance became unreachable after someone changed its security group and NACL. How do you recover quickly and prevent it? Senior
Recover:
- Check what changed in CloudTrail: AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, ReplaceNetworkAclEntry, with who and when.
- Revert the change, or attach a known good security group.
- Use Reachability Analyzer to confirm the path from source to the instance port.
aws ec2 create-network-insights-path --source igw-0abc1234 --destination i-0abc1234def567890 --protocol tcp --destination-port 443- Use Session Manager to check inside the OS if network is fine but the app is down.
Prevent: manage security groups in IaC with review, AWS Config rules for risky changes, and least privilege for ec2:Authorize/Revoke actions.
Q41. How do you script a safe "stop all non-production instances at night" job? Senior
- Select by tags, not by name: Env=dev or Env=test, and skip anything tagged Schedule=always-on.
aws ec2 describe-instances --filters Name=tag:Env,Values=dev,test Name=instance-state-name,Values=running --query "Reservations[].Instances[].InstanceId" --output text- Run the stop action from an EventBridge Scheduler rule calling Systems Manager Automation (AWS-StopEC2Instance) or a Lambda function.
- Do a dry run first:
aws ec2 stop-instances --instance-ids ... --dry-run. - Exclude instances in Auto Scaling groups (they would be replaced); set the group's desired capacity to zero instead.
- Log what was stopped and send a summary.
- Start them in the morning with a matching schedule.
Q42. An EC2 instance has a high steal time or noisy performance. How do you investigate? Senior
- Inside Linux, check
toporvmstat. On burstable T instances, a high "st" (steal) value usually means the instance is limited to its baseline because CPU credits are used up. - Check CPUCreditBalance in CloudWatch for T instances.
- Compare with similar instances on other types: if the problem is only on one instance, try stopping and starting it, which moves it to new hardware.
- Check EBS metrics: a volume at its IOPS or throughput limit makes the system look slow too.
- Check scheduled events: AWS may have planned maintenance for the host.
Fix with the right instance type for steady load, not by restarting again and again.
Q43. How do you handle an EC2 scheduled event, such as a host retirement notice? Senior
List events:
aws ec2 describe-instance-status --filters Name=event.code,Values=instance-retirement,system-reboot,instance-stop --query "InstanceStatuses[].[InstanceId,Events[0].Code,Events[0].NotBefore]" --output textOutput:
i-0abc1234def567890 instance-stop 2026-11-25T02:00:00ZAWS will stop this instance after that time because the underlying hardware needs work.
Action:
- For EBS-backed instances, stop and start it yourself at a good time; it moves to healthy hardware.
- For Auto Scaling groups, just terminate it; a new one replaces it.
- Some reboot events can be rescheduled.
Receive these events through AWS Health and EventBridge so nobody misses them.
Q44. You must give developers permission to launch instances, but only small types with required tags. How? Senior
Use IAM conditions on ec2:RunInstances:
- Allow only some instance types with the ec2:InstanceType condition, such as t3.* and t4g.*.
- Require tags at launch with aws:RequestTag/Env and aws:TagKeys.
- Allow ec2:CreateTags only when the action is RunInstances (ec2:CreateAction).
- Restrict to approved AMIs (by owner or tag) and subnets.
- Allow iam:PassRole only for an approved instance role.
Test with the IAM policy simulator, and add an SCP for guardrails across accounts, such as denying very large instance families.
Q45. How do you migrate an instance to a different Availability Zone? Senior
An instance cannot move between AZs directly, because its EBS volumes live in one AZ.
Steps:
- Create an AMI of the instance (or snapshots of its volumes).
- Launch a new instance from the AMI in the target AZ's subnet with the same settings (launch template helps).
- Move the Elastic IP or update DNS or the load balancer target.
- Test, then terminate the old instance.
Better long term: run stateless instances in an Auto Scaling group across several AZs, so AZ placement does not matter.
Q46. How do you troubleshoot an instance that starts and then immediately stops on its own? Senior
Common causes:
- An encrypted EBS volume whose KMS key is disabled, deleted, or not allowed for the user or EC2. The state reason shows "Client.InternalError" or a KMS error.
- An instance store or EBS limit problem, or a snapshot that is corrupt.
- The instance type does not support the AMI (for example missing ENA or NVMe drivers).
Check the state reason:
aws ec2 describe-instances --instance-ids i-0abc1234def567890 --query "Reservations[].Instances[].StateReason"Output:
[{"Code": "Client.InternalError", "Message": "Client.InternalError: Client error on launch"}]usually a KMS key permission problem. Check the key policy and the key state.
Q47. What is EC2 Auto Recovery and how is it different from Auto Scaling replacement? Senior
- Auto recovery moves the same instance to new hardware when a system status check fails. It keeps the instance ID, private IP addresses, Elastic IP and EBS volumes. Many current instance types have simplified automatic recovery turned on by default; you can also use a CloudWatch alarm with the recover action.
- Auto Scaling replacement terminates the unhealthy instance and launches a new one, with a new ID.
Use auto recovery for single, stateful instances that cannot easily be replaced. Use Auto Scaling for stateless fleets. Auto recovery does not help with OS-level problems (instance status check failures).
Q48. How would you find all EC2 instances still using IMDSv1 across an account and fix them? Senior
Find them:
aws ec2 describe-instances --query "Reservations[].Instances[?MetadataOptions.HttpTokens=='optional'].[InstanceId,Tags[?Key=='Name']|[0].Value]" --output textOutput:
i-0def5678abc123456 legacy-appThis instance still allows IMDSv1.
Check usage with the MetadataNoToken CloudWatch metric, to see if software still calls IMDSv1.
Fix:
aws ec2 modify-instance-metadata-options --instance-id i-0def5678abc123456 --http-tokens requiredPrevent: set the account default to IMDSv2 for new instances, require it in launch templates, and add an SCP or Config rule that denies IMDSv1.
Q49. How do you prove to an auditor which AMIs and instance types are running across all Regions? Senior
- Loop over Regions with the CLI, or use AWS Config advanced queries if Config is recording in all Regions (with an aggregator for many accounts).
for r in $(aws ec2 describe-regions --query "Regions[].RegionName" --output text); do aws ec2 describe-instances --region $r --query "Reservations[].Instances[].[InstanceId,ImageId,InstanceType]" --output text; doneOutput:
i-0abc1234def567890 ami-0123456789abcdef0 m6i.large- Compare the AMI IDs with your approved golden image list (for example AMIs tagged Approved=true or shared from the image account).
- Report any instance on an unapproved or deprecated AMI.
- Automate it as a scheduled job or a Config rule, so the evidence is always current instead of a one-time script.
Q50. How would you reduce the blast radius if one bad user data change breaks every new instance? Senior
- Treat user data like code: keep it in Git, review it and test it in a pipeline before it reaches the launch template.
- Keep user data small: call a versioned script or configuration tool, and fail loudly (exit codes, logs to CloudWatch).
- Roll out a new launch template version with an instance refresh that has checkpoints and auto rollback on alarms.
- Use health checks that test the real application, so broken instances are caught before all old instances are gone.
- Keep the previous version as $Default until the new one is proven.
This way one mistake affects a few instances, not the whole fleet.
5. Frequently asked questions
Do I need to memorise CLI syntax?
No. Know the main command names (describe-instances, run-instances, modify-instance-attribute) and how --query and --filters work. In real work you check aws ec2 <command> help.
Is the console enough for interviews?
For fresher roles, often yes. For DevOps and SRE roles, interviewers expect basic CLI and scripting, because automation is done in code, not by clicking.
What should I practise first?
Launch an instance from a launch template, change its type, create an AMI, and copy the AMI to another Region. Then read every field in describe-instances output.
6. Quick revision
--filtersreduces what AWS returns;--query(JMESPath) shapes the output on your side.- Launch templates have versions; use $Default or $Latest carefully in Auto Scaling groups.
- Changing instance type needs a stop (for EBS-backed instances) unless the type supports the change otherwise.
- T instances run on CPU credits; check CPUCreditBalance when a T instance becomes slow.
- Instance refresh replaces instances in an Auto Scaling group safely in batches.
7. Related chapters
- AWS EC2, EBS, Auto Scaling and Load Balancer Interview Questions and Answers (50 Questions)
- What Is Amazon EC2 and How Does It Work
- Linux on AWS EC2 Interview Questions and Answers for Cloud Engineers (50 Questions)
- Linux Troubleshooting Interview Questions on AWS EC2 Servers: SSH, Boot, Disk, CPU, Memory and Network (50 Questions)
- 1000 AWS Interview Questions and Answers for Freshers and Experienced (Complete Set)
This page is one part of the complete AWS interview question set. Open the full list here: All 2052 AWS interview questions.