Skip to content

AWS DevOps Interview Questions

AWS DevOps Interview Questions & Answers (1–50)

Section titled “AWS DevOps Interview Questions & Answers (1–50)”

Q1: What is AWS CodePipeline and how does it work?

Section titled “Q1: What is AWS CodePipeline and how does it work?”

Answer: AWS CodePipeline is a fully managed CI/CD service that orchestrates build, test, and deploy phases. Think of it as the glue that connects CodeCommit/GitHub → CodeBuild → CodeDeploy/ECS.

AWS DevOps toolchain:

Source Build Test Deploy
CodeCommit → CodeBuild → CodeBuild → CodeDeploy (EC2)
GitHub → ECS (container)
GitLab → EKS (kubernetes)
Bitbucket → Elastic Beanstalk
→ Lambda

Pipeline structure (JSON):

{
"pipeline": {
"name": "MyPipeline",
"roleArn": "arn:aws:iam::123456789012:role/PipelineRole",
"stages": [
{
"name": "Source",
"actions": [{
"name": "GitHub-Source",
"actionTypeId": {
"category": "Source",
"owner": "AWS",
"provider": "CodeStarSourceConnection",
"version": "1"
},
"configuration": {
"ConnectionArn": "arn:aws:codestar-connections:...",
"FullRepositoryId": "org/repo",
"BranchName": "main",
"DetectChanges": "true"
}
}]
},
{
"name": "Build",
"actions": [{
"name": "CodeBuild",
"actionTypeId": {
"category": "Build",
"owner": "AWS",
"provider": "CodeBuild",
"version": "1"
},
"configuration": {
"ProjectName": "MyBuildProject"
}
}]
},
{
"name": "Approve",
"actions": [{
"actionTypeId": {
"category": "Approval",
"owner": "AWS",
"provider": "Manual"
}
}]
},
{
"name": "Deploy",
"actions": [{
"actionTypeId": {
"category": "Deploy",
"owner": "AWS",
"provider": "ECS"
},
"configuration": {
"ClusterName": "MyCluster",
"ServiceName": "MyService",
"FileName": "imagedefinitions.json"
}
}]
}
]
}
}
Terminal window
# Create pipeline via CLI
aws codepipeline create-pipeline \
--cli-input-json file://pipeline.json
# Check pipeline status
aws codepipeline get-pipeline-state --name MyPipeline
# Manually trigger
aws codepipeline start-pipeline-execution --name MyPipeline
# View execution history
aws codepipeline list-pipeline-executions --pipeline-name MyPipeline

Interview tip: CodePipeline itself doesn’t build or deploy — it orchestrates other services. CodePipeline = workflow engine. CodeBuild = build runner. CodeDeploy = deployment executor. You can also use GitHub Actions or Jenkins in a CodePipeline stage.


Answer: CodeBuild is a fully managed build service that compiles code, runs tests, and produces deployment packages.

# buildspec.yml (placed in repo root)
version: 0.2
env:
variables:
IMAGE_REPO_NAME: myapp
parameter-store:
DB_PASSWORD: /myapp/db_password
secrets-manager:
API_KEY: myapp/api-key:key
phases:
install:
runtime-versions:
nodejs: 18
commands:
- npm install -g npm@latest
pre_build:
commands:
- echo Logging in to Amazon ECR...
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | \
docker login --username AWS \
--password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
- IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
build:
commands:
- echo Building Docker image...
- npm ci
- npm test
- docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
- docker tag $IMAGE_REPO_NAME:$IMAGE_TAG \
$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
post_build:
commands:
- echo Pushing Docker image...
- docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
- echo Writing image definitions file...
- printf '[{"name":"container","imageUri":"%s"}]' \
$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG \
> imagedefinitions.json
artifacts:
files:
- imagedefinitions.json
- appspec.yml
- taskdef.json
reports:
test-report:
files:
- 'test-results/**/*.xml'
file-format: JUNITXML
cache:
paths:
- '/root/.npm/**/*'
- 'node_modules/**/*'

Q3: What is AWS CodeDeploy and what deployment strategies does it support?

Section titled “Q3: What is AWS CodeDeploy and what deployment strategies does it support?”

Answer: CodeDeploy automates application deployments to EC2, Lambda, and ECS. It handles traffic shifting and rollback.

Deployment strategies:

StrategyWhat it doesUse case
AllAtOnceDeploy to all targets simultaneouslyDev/test (accepts downtime)
HalfAtATimeDeploy to 50% at a timeBalance speed + safety
OneAtATimeDeploy to one instance at a timeMax safety, slowest
CustomDefine exact % (e.g., 25%)Fine-grained control
ECS LinearShift 10% traffic every N minutesGradual canary
Lambda Canary10% for N minutes, then 100%Lambda blue-green
# appspec.yml for EC2 deployment
version: 0.0
os: linux
files:
- source: /app
destination: /opt/myapp
permissions:
- object: /opt/myapp
owner: ec2-user
group: ec2-user
hooks:
BeforeInstall: # Run before old version removed
- location: scripts/stop_server.sh
timeout: 60
runas: root
AfterInstall: # Run after new version installed
- location: scripts/install_deps.sh
timeout: 120
runas: ec2-user
ApplicationStart: # Start your application
- location: scripts/start_server.sh
timeout: 60
runas: ec2-user
ValidateService: # Verify deployment succeeded
- location: scripts/validate.sh
timeout: 60
runas: ec2-user
# If ValidateService fails, CodeDeploy AUTOMATICALLY ROLLS BACK!
Terminal window
# Create deployment
aws deploy create-deployment \
--application-name MyApp \
--deployment-group-name Production \
--deployment-config-name CodeDeployDefault.OneAtATime \
--github-location repository=org/repo,commitId=abc123
# Watch deployment status
aws deploy get-deployment --deployment-id d-XXXXXXXXX
# List deployments
aws deploy list-deployments \
--application-name MyApp \
--deployment-group-name Production \
--include-only-statuses InProgress Failed

Interview tip: CodeDeploy’s lifecycle hooks run in a specific order and if ValidateService script exits with non-zero, CodeDeploy automatically rolls back. Always implement a real health check in ValidateService (e.g., curl http://localhost/health).


Q4: What is the difference between ECS and EKS?

Section titled “Q4: What is the difference between ECS and EKS?”

Answer:

AspectECS (Elastic Container Service)EKS (Elastic Kubernetes Service)
OrchestratorAWS-proprietaryStandard Kubernetes
Learning curveLow (AWS-native concepts)High (full K8s knowledge needed)
Control plane costFree$0.10/hr (~$72/month)
Worker nodesEC2 or FargateEC2 or Fargate
EcosystemAWS tools onlyFull K8s ecosystem (Helm, Argo…)
PortabilityAWS-lockedPortable (same YAML works anywhere)
NetworkingAWS VPC CNIMultiple CNI options
Auto-scalingService Auto Scaling + FargateHPA + Cluster Autoscaler + KEDA
Best forAWS-first teams, simpler appsK8s expertise, multi-cloud plans

ECS concepts map to K8s:

ECS Task Definition ≠≡ K8s Pod spec
ECS Task ≠≡ K8s Pod
ECS Service ≠≡ K8s Deployment + Service
ECS Cluster ≠≡ K8s Node pool
ECR ≠≡ Container registry (works with both)
Fargate ≠≡ Serverless nodes (works with both)

Interview tip: “ECS is simpler and cheaper if you’re AWS-only. EKS is better if you need Kubernetes features (Helm, GitOps, KEDA, service mesh), have K8s expertise, or plan to be multi-cloud. Most startups start with ECS Fargate and migrate to EKS as complexity grows.”


Answer:

Terminal window
# 1. Create ECR repository
aws ecr create-repository --repository-name myapp
# 2. Build and push image
aws ecr get-login-password | docker login --username AWS \
--password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com
docker build -t myapp:$TAG .
docker tag myapp:$TAG $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/myapp:$TAG
docker push $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/myapp:$TAG
# 3. Register new task definition
aws ecs register-task-definition \
--cli-input-json file://taskdef.json
# 4. Update service
aws ecs update-service \
--cluster MyCluster \
--service MyService \
--task-definition myapp:$REVISION \
--force-new-deployment
# 5. Wait for deployment
aws ecs wait services-stable \
--cluster MyCluster \
--services MyService
{
"family": "myapp",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::...role/ecsTaskExecutionRole",
"containerDefinitions": [{
"name": "myapp",
"image": "123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:latest",
"portMappings": [{"containerPort": 3000, "protocol": "tcp"}],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/myapp",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
},
"secrets": [
{"name": "DB_PASSWORD", "valueFrom": "arn:aws:ssm:...parameter/db_password"}
]
}]
}

Answer:

Terminal window
# Create EKS cluster
eksctl create cluster \
--name production \
--region us-east-1 \
--nodegroup-name standard-workers \
--node-type m5.large \
--nodes 3 \
--nodes-min 2 \
--nodes-max 5 \
--managed
# Update kubeconfig
aws eks update-kubeconfig --name production --region us-east-1
# Configure IAM for CI/CD (IRSA — IAM Roles for Service Accounts)
eksctl create iamserviceaccount \
--name codebuild-deployer \
--namespace production \
--cluster production \
--attach-policy-arn arn:aws:iam::aws:policy/AmazonEKSClusterPolicy \
--approve
# In GitHub Actions
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
aws-region: us-east-1
- name: Update kubeconfig
run: aws eks update-kubeconfig --name production --region us-east-1
- name: Deploy
run: kubectl apply -f k8s/

Q7: What is CloudFormation and how does it work?

Section titled “Q7: What is CloudFormation and how does it work?”

Answer:

cloudformation-stack.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: ECS Fargate Application Stack
Parameters:
Environment:
Type: String
AllowedValues: [dev, staging, production]
ImageTag:
Type: String
Resources:
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Sub ${Environment}-cluster
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Sub ${Environment}-myapp
RequiresCompatibilities: [FARGATE]
NetworkMode: awsvpc
Cpu: 256
Memory: 512
ContainerDefinitions:
- Name: myapp
Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/myapp:${ImageTag}
PortMappings:
- ContainerPort: 3000
ECSService:
Type: AWS::ECS::Service
Properties:
Cluster: !Ref ECSCluster
TaskDefinition: !Ref TaskDefinition
DesiredCount: 2
LaunchType: FARGATE
Outputs:
ClusterName:
Value: !Ref ECSCluster
Export:
Name: !Sub ${Environment}-ClusterName
Terminal window
# Deploy stack
aws cloudformation deploy \
--template-file cloudformation-stack.yaml \
--stack-name production-myapp \
--parameter-overrides Environment=production ImageTag=v1.2.0 \
--capabilities CAPABILITY_IAM
# View stack events
aws cloudformation describe-stack-events \
--stack-name production-myapp
# Delete stack
aws cloudformation delete-stack --stack-name production-myapp

Q8: How do you use AWS CDK for infrastructure?

Section titled “Q8: How do you use AWS CDK for infrastructure?”

Answer:

lib/app-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecr from 'aws-cdk-lib/aws-ecr';
export class AppStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'AppVPC', { maxAzs: 2 });
const cluster = new ecs.Cluster(this, 'AppCluster', { vpc });
const repo = ecr.Repository.fromRepositoryName(this, 'Repo', 'myapp');
const taskDef = new ecs.FargateTaskDefinition(this, 'TaskDef', {
memoryLimitMiB: 512,
cpu: 256,
});
taskDef.addContainer('App', {
image: ecs.ContainerImage.fromEcrRepository(repo, 'latest'),
portMappings: [{ containerPort: 3000 }],
logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'myapp' }),
});
new ecs.FargateService(this, 'Service', {
cluster,
taskDefinition: taskDef,
desiredCount: 3,
});
}
}
Terminal window
# Deploy CDK stack
npm install -g aws-cdk
cdk bootstrap
cdk synth # Preview CloudFormation
cdk diff # Show changes
cdk deploy # Deploy
cdk destroy # Teardown

Q9: How do you set up CloudWatch monitoring for applications?

Section titled “Q9: How do you set up CloudWatch monitoring for applications?”

Answer:

Terminal window
# Create CloudWatch log group
aws logs create-log-group --log-group-name /myapp/production
# Set retention
aws logs put-retention-policy \
--log-group-name /myapp/production \
--retention-in-days 30
# Create metric filter for errors
aws logs put-metric-filter \
--log-group-name /myapp/production \
--filter-name ErrorCount \
--filter-pattern "[timestamp, level=ERROR, ...]" \
--metric-transformations \
metricName=ErrorCount,metricNamespace=MyApp,metricValue=1
# Create alarm
aws cloudwatch put-metric-alarm \
--alarm-name HighErrorRate \
--metric-name ErrorCount \
--namespace MyApp \
--period 300 \
--evaluation-periods 2 \
--threshold 10 \
--comparison-operator GreaterThanThreshold \
--alarm-actions arn:aws:sns:us-east-1:123456789012:AlertTopic

Q10: How do you implement distributed tracing with AWS X-Ray?

Section titled “Q10: How do you implement distributed tracing with AWS X-Ray?”

Answer:

// Node.js — instrument with X-Ray
const AWSXRay = require('aws-xray-sdk');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const http = AWSXRay.captureHTTPs(require('http'));
const app = express();
app.use(AWSXRay.express.openSegment('MyApp'));
app.get('/api/users', async (req, res) => {
// Create subsegment for DB call
const segment = AWSXRay.getSegment();
const sub = segment.addNewSubsegment('fetchUsers');
const users = await db.query('SELECT * FROM users');
sub.close();
res.json(users);
});
app.use(AWSXRay.express.closeSegment());
Terminal window
# View X-Ray traces
aws xray get-trace-summaries \
--start-time $(date -d '1 hour ago' +%s) \
--end-time $(date +%s)

Q11: How do you set up a VPC for a production application?

Section titled “Q11: How do you set up a VPC for a production application?”

Answer:

Terminal window
# Create VPC
aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications \
'ResourceType=vpc,Tags=[{Key=Name,Value=prod-vpc}]'
# Create public subnets (in 2 AZs)
aws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.1.0/24 --availability-zone us-east-1a
aws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.2.0/24 --availability-zone us-east-1b
# Create private subnets
aws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.10.0/24 --availability-zone us-east-1a
aws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.11.0/24 --availability-zone us-east-1b
# Internet Gateway for public subnets
aws ec2 create-internet-gateway
aws ec2 attach-internet-gateway --internet-gateway-id igw-xxx --vpc-id vpc-xxx
# NAT Gateway for private subnets
aws ec2 allocate-address --domain vpc
aws ec2 create-nat-gateway --subnet-id subnet-public-1 --allocation-id eipalloc-xxx

Q12: How do you set up Application Load Balancer with ECS?

Section titled “Q12: How do you set up Application Load Balancer with ECS?”

Answer:

Terminal window
# Create ALB
aws elbv2 create-load-balancer \
--name prod-alb \
--subnets subnet-pub-1 subnet-pub-2 \
--security-groups sg-alb \
--type application
# Create target group
aws elbv2 create-target-group \
--name myapp-tg \
--protocol HTTP \
--port 3000 \
--vpc-id vpc-xxx \
--target-type ip \
--health-check-path /health \
--health-check-interval-seconds 30 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 5
# Create HTTPS listener
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--protocol HTTPS \
--port 443 \
--certificates CertificateArn=arn:aws:acm:... \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:...

Answer:

Terminal window
# AWS Secrets Manager (recommended)
aws secretsmanager create-secret \
--name /production/db \
--secret-string '{"host":"db.internal","user":"app","password":"secret"}'
# Retrieve in application
aws secretsmanager get-secret-value \
--secret-id /production/db \
--query SecretString \
--output text | jq -r .password
# Auto-rotate secret (requires Lambda rotation function)
aws secretsmanager rotate-secret \
--secret-id /production/db \
--rotation-lambda-arn arn:aws:lambda:...
# SSM Parameter Store (cheaper, simpler)
aws ssm put-parameter \
--name /production/api-key \
--value "my-api-key-value" \
--type SecureString \
--key-id alias/aws/ssm
aws ssm get-parameter \
--name /production/api-key \
--with-decryption \
--query Parameter.Value

Q14: How does IAM work for CI/CD pipelines?

Section titled “Q14: How does IAM work for CI/CD pipelines?”

Answer:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:PutImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ecs:UpdateService",
"ecs:DescribeServices",
"ecs:RegisterTaskDefinition"
],
"Resource": "arn:aws:ecs:us-east-1:123456789012:service/production/*"
}
]
}
Terminal window
# GitHub Actions OIDC (no long-lived credentials)
aws iam create-open-id-connect-provider \
--url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com
# Trust policy for role
{
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:sub": "repo:org/repo:ref:refs/heads/main"
}
}
}

Q15: How do you deploy Lambda functions in a CI/CD pipeline?

Section titled “Q15: How do you deploy Lambda functions in a CI/CD pipeline?”

Answer:

Terminal window
# Using AWS SAM
sam build
sam deploy \
--stack-name my-lambda \
--s3-bucket my-deployment-bucket \
--capabilities CAPABILITY_IAM \
--parameter-overrides Environment=production
# GitHub Actions for Lambda deployment
- name: Deploy Lambda
uses: aws-actions/aws-cloudformation-github-deploy@v1
with:
name: my-lambda-stack
template: template.yaml
capabilities: CAPABILITY_IAM
parameter-overrides: |
Environment=production
ImageTag=${{ github.sha }}
# SAM template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Timeout: 30
Runtime: nodejs18.x
Environment:
Variables:
NODE_ENV: !Ref Environment
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
Handler: dist/handler.main
CodeUri: ./
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5Minutes # Canary deployment
Events:
Api:
Type: Api
Properties:
Path: /api/{proxy+}
Method: ANY

Back to DevOps Q&A Index


Q16: What is the difference between AWS Regions, Availability Zones, and Edge Locations?

Section titled “Q16: What is the difference between AWS Regions, Availability Zones, and Edge Locations?”

Answer:

ConceptDescriptionCount (approx)
RegionGeographic area (e.g., us-east-1)33+ regions
Availability Zone (AZ)Data center within a region2-6 per region
Edge LocationCloudFront CDN cache point400+ worldwide
us-east-1 (Region: N. Virginia)
├── us-east-1a (AZ — Data Center 1)
├── us-east-1b (AZ — Data Center 2)
├── us-east-1c (AZ — Data Center 3)
└── us-east-1d (AZ — Data Center 4)
Best practice: Deploy across 2+ AZs for high availability
Best practice: Deploy across 2+ regions for disaster recovery
Terminal window
# List regions
aws ec2 describe-regions --output table
# List AZs in region
aws ec2 describe-availability-zones --region us-east-1

Q17: What is the difference between EC2 instance types?

Section titled “Q17: What is the difference between EC2 instance types?”

Answer:

FamilyOptimized forExampleUse Case
t3/t4gBurstable performancet3.mediumDev, low traffic
m6iGeneral purposem6i.xlargeWeb servers, APIs
c6iCompute-optimizedc6i.2xlargeCPU-intensive, CI runners
r6iMemory-optimizedr6i.4xlargeDatabases, caching
g4dnGPUg4dn.xlargeML, rendering
i3Storage-optimizedi3.largeHigh I/O databases
Terminal window
# Check instance pricing
aws ec2 describe-spot-price-history \
--instance-types t3.medium \
--product-descriptions "Linux/UNIX"
# Use Spot Instances for 60-90% savings (non-critical workloads)
aws ec2 request-spot-instances \
--spot-price "0.05" \
--instance-count 1 \
--type "one-time" \
--launch-specification file://spec.json

Q18: What is Auto Scaling and how does it work?

Section titled “Q18: What is Auto Scaling and how does it work?”

Answer: Auto Scaling automatically adjusts EC2 instance count based on demand.

CloudWatch Alarm: CPU > 70% for 5 minutes
Auto Scaling Group: Launch 2 more instances
Target Group: New instances added to load balancer
CloudWatch Alarm: CPU < 30% for 15 minutes
Auto Scaling Group: Terminate excess instances
Terminal window
# Create Auto Scaling Group
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name myapp-asg \
--launch-template "LaunchTemplateName=myapp-lt,Version=1" \
--min-size 2 \
--max-size 10 \
--desired-capacity 3 \
--vpc-zone-identifier "subnet-1,subnet-2" \
--target-group-arns arn:aws:elasticloadbalancing:...
# Create scaling policy (Target Tracking — recommended)
aws autoscaling put-scaling-policy \
--auto-scaling-group-name myapp-asg \
--policy-name cpu-target-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 70.0
}'

Q19: What is the difference between ALB and NLB?

Section titled “Q19: What is the difference between ALB and NLB?”

Answer:

FeatureALB (Application LB)NLB (Network LB)
LayerL7 (HTTP/HTTPS)L4 (TCP/UDP)
RoutingPath, host, headersIP, port
WebSocket✅ Yes✅ Yes
Latency~1ms extraUltra-low
Static IP❌ No✅ Yes
TLS termination✅ Yes✅ Yes
Use caseWeb apps, microservicesGaming, IoT, financial trading
Terminal window
# ALB — content-based routing
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:... \
--conditions '[
{"Field":"path-pattern","Values":["/api/*"]}
]' \
--actions '[
{"Type":"forward","TargetGroupArn":"arn:...api-tg"}
]' \
--priority 10
# Route /api/* to API service
# Route /* to frontend service

Q20: What is S3 and how is it used in DevOps?

Section titled “Q20: What is S3 and how is it used in DevOps?”

Answer: S3 (Simple Storage Service) is object storage — used heavily in DevOps pipelines.

Terminal window
# DevOps use cases for S3:
# 1. Static website hosting
aws s3 website s3://myapp-frontend \
--index-document index.html \
--error-document 404.html
# 2. Store Terraform state
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "production/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-lock" # State locking
}
}
# 3. Artifact storage
aws s3 cp ./dist.tar.gz s3://artifacts/myapp/v1.5.0/dist.tar.gz
# 4. Log archiving
aws s3 sync /var/log/myapp s3://logs-bucket/myapp/$(date +%Y/%m/%d)/
# 5. Backup storage
aws s3 cp db-backup.sql.gz s3://backups/postgres/$(date +%Y%m%d).sql.gz
# S3 versioning (protect against accidental deletes)
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled
# S3 lifecycle (auto-delete old artifacts)
aws s3api put-bucket-lifecycle-configuration \
--bucket artifacts \
--lifecycle-configuration '{
"Rules": [{
"Id": "DeleteOldArtifacts",
"Status": "Enabled",
"Expiration": {"Days": 90}
}]
}'

Answer: IAM (Identity and Access Management) controls WHO can do WHAT to WHICH resources.

// IAM Policy = JSON document with permissions
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Deny",
"Action": "s3:DeleteObject",
"Resource": "*"
}
]
}
Terminal window
# IAM entities:
# User: Individual person/service with credentials
# Group: Collection of users with same permissions
# Role: Temporary permissions (EC2, Lambda, CI/CD)
# Policy: JSON document defining permissions
# Create role for EC2 to access S3
aws iam create-role \
--role-name EC2S3ReadRole \
--assume-role-policy-document '{
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
aws iam attach-role-policy \
--role-name EC2S3ReadRole \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# Check effective permissions
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::123456789012:role/MyRole \
--action-names s3:GetObject

Principle of Least Privilege: Give only the minimum permissions needed.


Q22: What is AWS VPC and how do you set it up for production?

Section titled “Q22: What is AWS VPC and how do you set it up for production?”

Answer: VPC (Virtual Private Cloud) is your isolated network in AWS.

Terminal window
# Production VPC architecture:
# Public subnets → Internet-facing (ALB, NAT Gateway, Bastion)
# Private subnets → App servers, databases (no direct internet)
# Isolated subnets → Databases only (no NAT gateway access)
# Create VPC
VPC_ID=$(aws ec2 create-vpc \
--cidr-block 10.0.0.0/16 \
--query Vpc.VpcId --output text)
aws ec2 create-tags \
--resources $VPC_ID \
--tags Key=Name,Value=production-vpc
# Enable DNS
aws ec2 modify-vpc-attribute --vpc-id $VPC_ID \
--enable-dns-hostnames
# Create subnets (2 AZs for HA)
# Public subnets
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.1.0/24 --availability-zone us-east-1a
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.2.0/24 --availability-zone us-east-1b
# Private subnets (app layer)
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.10.0/24 --availability-zone us-east-1a
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.11.0/24 --availability-zone us-east-1b
# Database subnets (no internet)
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.20.0/24 --availability-zone us-east-1a
aws ec2 create-subnet --vpc-id $VPC_ID \
--cidr-block 10.0.21.0/24 --availability-zone us-east-1b
# Internet Gateway (for public subnets)
IGW_ID=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)
aws ec2 attach-internet-gateway --internet-gateway-id $IGW_ID --vpc-id $VPC_ID
# NAT Gateway (for private subnets to reach internet)
EIP=$(aws ec2 allocate-address --domain vpc --query AllocationId --output text)
aws ec2 create-nat-gateway \
--subnet-id <public-subnet-id> \
--allocation-id $EIP

Answer:

FeatureSecurity GroupNACL
LevelInstance levelSubnet level
StateStatefulStateless
RulesAllow onlyAllow and Deny
DefaultDeny all in, allow all outAllow all
EvaluationAll rules evaluatedRules in number order
Terminal window
# Security Group — attached to instances
# Stateful: If you allow inbound 80, response is auto-allowed outbound
# Create web server security group
aws ec2 create-security-group \
--group-name web-sg \
--description "Web servers" \
--vpc-id $VPC_ID
# Allow inbound HTTP from ALB security group only
aws ec2 authorize-security-group-ingress \
--group-id sg-web \
--protocol tcp \
--port 80 \
--source-group sg-alb # Only from ALB, not internet
# NACL — attached to subnets
# Stateless: Must explicitly allow both inbound AND outbound
aws ec2 create-network-acl \
--vpc-id $VPC_ID
aws ec2 create-network-acl-entry \
--network-acl-id acl-xxx \
--rule-number 100 \
--protocol tcp \
--port-range From=80,To=80 \
--cidr-block 0.0.0.0/0 \
--rule-action allow \
--ingress
# Block specific IP (NACL can DENY, SG cannot)
aws ec2 create-network-acl-entry \
--network-acl-id acl-xxx \
--rule-number 50 \
--protocol -1 \
--cidr-block 1.2.3.4/32 \
--rule-action deny \
--ingress

Q24: What is AWS RDS and how do you set it up for production?

Section titled “Q24: What is AWS RDS and how do you set it up for production?”

Answer: RDS (Relational Database Service) is managed database service.

Terminal window
# Create RDS instance (production setup)
aws rds create-db-instance \
--db-instance-identifier prod-postgres \
--db-instance-class db.r6g.xlarge \
--engine postgres \
--engine-version 15.4 \
--master-username admin \
--master-user-password $(aws secretsmanager get-secret-value \
--secret-id /prod/db-password --query SecretString --output text) \
--allocated-storage 100 \
--storage-type gp3 \
--storage-encrypted \
--kms-key-id alias/aws/rds \
--vpc-security-group-ids sg-db \
--db-subnet-group-name production-db-subnet-group \
--backup-retention-period 7 \
--preferred-backup-window "02:00-03:00" \
--multi-az \ # HA: Standby in another AZ
--auto-minor-version-upgrade \
--deletion-protection # Prevent accidental deletion
# Create read replica (for read-heavy workloads)
aws rds create-db-instance-read-replica \
--db-instance-identifier prod-postgres-read-1 \
--source-db-instance-identifier prod-postgres \
--db-instance-class db.r6g.large
# RDS Proxy (connection pooling — critical for Lambda/ECS)
aws rds create-db-proxy \
--db-proxy-name myapp-proxy \
--engine-family POSTGRESQL \
--auth '[{"AuthScheme":"SECRETS","SecretArn":"arn:aws:secretsmanager:...","IAMAuth":"DISABLED"}]' \
--role-arn arn:aws:iam::...role/rds-proxy-role \
--vpc-subnet-ids subnet-1 subnet-2 \
--vpc-security-group-ids sg-db

Q25: How does AWS Route 53 work in production?

Section titled “Q25: How does AWS Route 53 work in production?”

Answer: Route 53 is AWS’s DNS service with advanced routing capabilities.

Terminal window
# Create hosted zone
aws route53 create-hosted-zone \
--name myapp.com \
--caller-reference $(date +%s)
# Simple A record
aws route53 change-resource-record-sets \
--hosted-zone-id Z123456 \
--change-batch '{
"Changes": [{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "myapp.com",
"Type": "A",
"AliasTarget": {
"HostedZoneId": "Z35SXDOTRQ7X7K",
"DNSName": "my-alb-123456.us-east-1.elb.amazonaws.com",
"EvaluateTargetHealth": true
}
}
}]
}'
# Weighted routing (canary/blue-green)
# Route 90% to v1, 10% to v2
aws route53 change-resource-record-sets --hosted-zone-id Z123 \
--change-batch '{
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "myapp.com",
"Type": "A",
"SetIdentifier": "v1",
"Weight": 90,
"AliasTarget": {
"DNSName": "alb-v1.us-east-1.elb.amazonaws.com",
"HostedZoneId": "..."
}
}
},
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "myapp.com",
"Type": "A",
"SetIdentifier": "v2",
"Weight": 10,
"AliasTarget": {
"DNSName": "alb-v2.us-east-1.elb.amazonaws.com",
"HostedZoneId": "..."
}
}
}
]
}'
# Health-check based failover
# Route to us-east-1 normally, failover to eu-west-1 if unhealthy

Q26: What is AWS CloudTrail and why is it important?

Section titled “Q26: What is AWS CloudTrail and why is it important?”

Answer: CloudTrail records all API calls made to AWS — your audit log.

Terminal window
# CloudTrail records:
# - Who made the API call (user/role/service)
# - What action was taken (CreateBucket, DeleteInstance, etc.)
# - When it happened (timestamp)
# - From where (IP address)
# - What resources were affected
# Enable CloudTrail (should always be ON)
aws cloudtrail create-trail \
--name my-audit-trail \
--s3-bucket-name my-cloudtrail-logs \
--include-global-service-events \
--is-multi-region-trail \
--enable-log-file-validation
aws cloudtrail start-logging --name my-audit-trail
# Example query: Who deleted our S3 bucket?
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=DeleteBucket \
--start-time 2024-01-01 \
--end-time 2024-01-31
# Security alert: Someone made your S3 bucket public
# CloudTrail log shows: PutBucketAcl → public-read → by user X at time Y from IP Z
# Integrate with CloudWatch for alerts
aws logs put-metric-filter \
--log-group-name CloudTrail/DefaultLogGroup \
--filter-name RootAccountUsage \
--filter-pattern '{ $.userIdentity.type = "Root" }' \
--metric-transformations metricName=RootAccountUsage,metricNamespace=Security,metricValue=1

Q27: What is AWS Config and how does it help compliance?

Section titled “Q27: What is AWS Config and how does it help compliance?”

Answer: AWS Config continuously records and evaluates AWS resource configurations for compliance.

Terminal window
# AWS Config tracks:
# - Current state of all AWS resources
# - Historical configuration changes
# - Relationships between resources
# Enable AWS Config
aws configservice put-configuration-recorder \
--configuration-recorder name=default,roleARN=arn:aws:iam::123456789012:role/config-role
aws configservice put-delivery-channel \
--delivery-channel name=default,s3BucketName=config-bucket
aws configservice start-configuration-recorder --configuration-recorder-name default
# Config Rules — automated compliance checks
aws configservice put-config-rule \
--config-rule '{
"ConfigRuleName": "s3-bucket-public-read-prohibited",
"Source": {
"Owner": "AWS",
"SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED"
}
}'
# Check compliance
aws configservice describe-compliance-by-config-rule \
--config-rule-names s3-bucket-public-read-prohibited
# Common managed rules:
# - encrypted-volumes
# - rds-instance-public-access-check
# - s3-bucket-public-read-prohibited
# - iam-root-access-key-check
# - mfa-enabled-for-iam-console-access

Answer:

FeatureSQS (Queue)SNS (Topic)
TypePull-based queuePush-based pub/sub
ConsumersOne consumer per messageMultiple subscribers
PersistenceMessages stored until consumedMessages not stored
PatternTask queues, worker poolsFan-out, notifications
ExampleProcess ordersNotify all services of new order
Terminal window
# SQS — Order processing queue
# Producer sends order → SQS Queue → Worker pulls and processes
# Create SQS queue
aws sqs create-queue \
--queue-name orders-queue \
--attributes '{
"VisibilityTimeout": "30",
"MessageRetentionPeriod": "86400",
"ReceiveMessageWaitTimeSeconds": "20"
}'
# Send message
aws sqs send-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123/orders-queue \
--message-body '{"orderId": "123", "amount": 99.99}'
# Receive and process
aws sqs receive-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123/orders-queue \
--max-number-of-messages 10
# SNS — notify multiple services when new order arrives
aws sns create-topic --name order-events
# Subscribe SQS queue to SNS topic
aws sns subscribe \
--topic-arn arn:aws:sns:...:order-events \
--protocol sqs \
--notification-endpoint arn:aws:sqs:...:inventory-queue
aws sns subscribe \
--topic-arn arn:aws:sns:...:order-events \
--protocol email \
--notification-endpoint admin@myapp.com
# Publish event — all subscribers receive it
aws sns publish \
--topic-arn arn:aws:sns:...:order-events \
--message '{"event": "ORDER_PLACED", "orderId": "123"}'

Q29: How do you implement AWS WAF for security?

Section titled “Q29: How do you implement AWS WAF for security?”

Answer: WAF (Web Application Firewall) protects against common web attacks.

Terminal window
# Common WAF use cases:
# - Block SQL injection
# - Block XSS
# - Rate limiting (DDoS protection)
# - Geo-blocking
# - Block known malicious IPs
# Create WAF WebACL
aws wafv2 create-web-acl \
--name myapp-waf \
--scope REGIONAL \
--default-action Allow={} \
--rules '[
{
"Name": "AWSManagedRulesCommonRuleSet",
"Priority": 1,
"OverrideAction": {"None": {}},
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesCommonRuleSet"
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "CommonRuleSet"
}
},
{
"Name": "RateLimit",
"Priority": 2,
"Action": {"Block": {}},
"Statement": {
"RateBasedStatement": {
"Limit": 1000,
"AggregateKeyType": "IP"
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "RateLimit"
}
}
]' \
--visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=myapp-waf
# Associate with ALB
aws wafv2 associate-web-acl \
--web-acl-arn arn:aws:wafv2:... \
--resource-arn arn:aws:elasticloadbalancing:...

Q30: What is AWS Secrets Manager vs SSM Parameter Store?

Section titled “Q30: What is AWS Secrets Manager vs SSM Parameter Store?”

Answer:

FeatureSecrets ManagerSSM Parameter Store
Cost$0.40/secret/monthFree (Standard tier)
Auto-rotation✅ Built-in❌ Manual (with Lambda)
Cross-account✅ Yes❌ No
Size limit65KB4KB (Standard), 8KB (Advanced)
Use forDB passwords, API keysConfig values, feature flags
Terminal window
# Secrets Manager — for sensitive secrets with rotation
aws secretsmanager create-secret \
--name /production/database \
--secret-string '{
"host": "prod-db.xxx.us-east-1.rds.amazonaws.com",
"port": "5432",
"username": "app",
"password": "super-secret-password"
}'
# Enable auto-rotation (every 30 days)
aws secretsmanager rotate-secret \
--secret-id /production/database \
--rotation-lambda-arn arn:aws:lambda:...rotation-function \
--rotation-rules AutomaticallyAfterDays=30
# SSM Parameter Store — for configuration
aws ssm put-parameter \
--name /production/app/log-level \
--value "info" \
--type String
aws ssm put-parameter \
--name /production/app/api-key \
--value "key-value" \
--type SecureString # Encrypted with KMS
# Access in application
aws secretsmanager get-secret-value --secret-id /production/database
aws ssm get-parameter --name /production/app/api-key --with-decryption

Q31: How do you implement AWS CloudFront for CDN?

Section titled “Q31: How do you implement AWS CloudFront for CDN?”

Answer: CloudFront is AWS’s CDN — caches content at edge locations for low latency.

Terminal window
# Create CloudFront distribution for S3 static site
aws cloudfront create-distribution \
--distribution-config '{
"CallerReference": "myapp-dist-1",
"Origins": {
"Quantity": 1,
"Items": [{
"Id": "S3Origin",
"DomainName": "myapp.s3.amazonaws.com",
"S3OriginConfig": {
"OriginAccessIdentity": "origin-access-identity/cloudfront/XXXX"
}
}]
},
"DefaultCacheBehavior": {
"TargetOriginId": "S3Origin",
"ViewerProtocolPolicy": "redirect-to-https",
"CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
"Compress": true
},
"PriceClass": "PriceClass_100",
"Enabled": true,
"HttpVersion": "http2and3",
"ViewerCertificate": {
"AcmCertificateArn": "arn:aws:acm:us-east-1:...",
"SslSupportMethod": "sni-only",
"MinimumProtocolVersion": "TLSv1.2_2021"
}
}'
# Invalidate cache after deployment
aws cloudfront create-invalidation \
--distribution-id E1XXXXXXXXXXXXX \
--paths "/*" # Invalidate everything
# or specific files:
# --paths "/index.html" "/static/js/*"

Q32: What is AWS KMS and how do you use it?

Section titled “Q32: What is AWS KMS and how do you use it?”

Answer: KMS (Key Management Service) — manage encryption keys for your AWS services.

Terminal window
# Create KMS key
aws kms create-key \
--description "Production app encryption key" \
--key-usage ENCRYPT_DECRYPT \
--key-spec SYMMETRIC_DEFAULT
# Create alias (friendly name)
aws kms create-alias \
--alias-name alias/prod-app-key \
--target-key-id arn:aws:kms:...
# Encrypt data
aws kms encrypt \
--key-id alias/prod-app-key \
--plaintext "my-sensitive-data" \
--output text --query CiphertextBlob | base64 -d > encrypted.bin
# Decrypt data
aws kms decrypt \
--ciphertext-blob fileb://encrypted.bin \
--output text --query Plaintext | base64 -d
# Use KMS for:
# - S3 encryption: aws s3api put-bucket-encryption
# - RDS encryption: --storage-encrypted --kms-key-id
# - EBS encryption: aws ec2 create-volume --encrypted
# - Secrets Manager: --kms-key-id
# - Envelope encryption in application code (AWS SDK)

Q33: How does AWS Lambda work and when should you use it?

Section titled “Q33: How does AWS Lambda work and when should you use it?”

Answer: Lambda runs code without managing servers — pay per invocation.

Terminal window
# Lambda characteristics:
# - Runs up to 15 minutes
# - Up to 10GB memory
# - Up to 10GB ephemeral storage
# - Scales automatically (1000s of concurrent)
# - Pay per 100ms of execution
# Create Lambda function
aws lambda create-function \
--function-name myapp-api \
--runtime nodejs18.x \
--handler dist/handler.main \
--role arn:aws:iam::123456789012:role/lambda-role \
--zip-file fileb://function.zip \
--timeout 30 \
--memory-size 512 \
--environment Variables={NODE_ENV=production,LOG_LEVEL=info} \
--tracing-config Mode=Active
# Invoke Lambda
aws lambda invoke \
--function-name myapp-api \
--payload '{"action": "list-users"}' \
output.json
# Lambda triggers:
# - API Gateway (HTTP API)
# - S3 events (file upload processing)
# - SQS (queue processing)
# - CloudWatch Events (scheduled cron)
# - SNS notifications
# - DynamoDB streams
# When to USE Lambda:
# ✅ Event-driven, sporadic workloads
# ✅ Simple REST APIs
# ✅ File processing (resize image on S3 upload)
# ✅ Scheduled jobs (replace cron)
# When NOT to use Lambda:
# ❌ Long-running processes (> 15 min)
# ❌ High-throughput APIs (ECS is cheaper)
# ❌ Stateful applications
# ❌ WebSocket servers

Q34: What is AWS ECS Fargate vs EC2 launch type?

Section titled “Q34: What is AWS ECS Fargate vs EC2 launch type?”

Answer:

FeatureECS FargateECS EC2
Server management❌ None✅ You manage
CostHigher per vCPU/memoryLower if right-sized
ScalingFast (no instance warmup)Slower (EC2 launch time)
ControlLimitedFull OS access
Best forMost containerized appsGPU, custom AMI needs
Terminal window
# Fargate task — no EC2 management
aws ecs register-task-definition \
--family myapp \
--network-mode awsvpc \
--requires-compatibilities FARGATE \
--cpu 256 \ # 0.25 vCPU
--memory 512 \
--execution-role-arn arn:aws:iam::...role/ecsTaskExecutionRole \
--task-role-arn arn:aws:iam::...role/ecsTaskRole \
--container-definitions '[{
"name": "myapp",
"image": "123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:latest",
"portMappings": [{"containerPort": 3000, "protocol": "tcp"}],
"environment": [{"name": "NODE_ENV", "value": "production"}],
"secrets": [{"name": "DB_PASSWORD", "valueFrom": "arn:aws:ssm:..."}],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/myapp",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
},
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 15
}
}]'

Q35: How do you implement cost optimization in AWS?

Section titled “Q35: How do you implement cost optimization in AWS?”

Answer:

Terminal window
# 1. Right-sizing — find oversized instances
aws ce get-rightsizing-recommendation \
--service EC2
# 2. Reserved Instances — save 40-60% vs On-Demand
aws ec2 purchase-reserved-instances-offering \
--reserved-instances-offering-id ... \
--instance-count 3
# Commit to 1-3 years for max savings
# 3. Savings Plans — flexible alternative to RIs
# Commit to $/hour spend, applies to any EC2/Fargate/Lambda
# 4. Spot Instances — 70-90% savings, can be interrupted
aws ec2 request-spot-fleet \
--spot-fleet-request-config '{
"IamFleetRole": "arn:aws:iam::...role/spot-fleet",
"AllocationStrategy": "diversified",
"TargetCapacity": 10,
"LaunchSpecifications": [...]
}'
# 5. S3 Intelligent-Tiering
aws s3api put-bucket-intelligent-tiering-configuration \
--bucket my-bucket \
--id EntireBucket \
--intelligent-tiering-configuration '{
"Id": "EntireBucket",
"Status": "Enabled",
"Tierings": [{"Days": 90, "AccessTier": "ARCHIVE_ACCESS"}]
}'
# 6. AWS Cost Explorer — identify waste
aws ce get-cost-and-usage \
--time-period Start=2024-01-01,End=2024-01-31 \
--granularity MONTHLY \
--metrics BlendedCost \
--group-by Type=DIMENSION,Key=SERVICE
# 7. Delete unused resources
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=stopped"
aws ebs describe-volumes --filters "Name=status,Values=available"
aws ec2 describe-snapshots --owner-ids self

Q36: What is AWS ECR and how do you use it?

Section titled “Q36: What is AWS ECR and how do you use it?”

Answer: ECR (Elastic Container Registry) is a managed Docker image registry.

Terminal window
# Create ECR repository
aws ecr create-repository \
--repository-name myapp \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS \
--image-tag-mutability IMMUTABLE
# Authenticate Docker to ECR
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS \
--password-stdin 123456789.dkr.ecr.us-east-1.amazonaws.com
# Build and push image
docker build -t myapp:1.0 .
docker tag myapp:1.0 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:1.0
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:1.0
# Set lifecycle policy (delete old images)
aws ecr put-lifecycle-policy \
--repository-name myapp \
--lifecycle-policy-text '{
"rules": [{
"rulePriority": 1,
"description": "Keep last 10 images",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 10
},
"action": {"type": "expire"}
}]
}'
# View scan results
aws ecr describe-image-scan-findings \
--repository-name myapp \
--image-id imageTag=1.0

Q37: How do you implement AWS GuardDuty for threat detection?

Section titled “Q37: How do you implement AWS GuardDuty for threat detection?”

Answer: GuardDuty continuously monitors for malicious activity using ML and threat intelligence.

Terminal window
# Enable GuardDuty
aws guardduty create-detector \
--enable \
--finding-publishing-frequency SIX_HOURS
# GuardDuty monitors:
# - CloudTrail logs (API activity)
# - VPC Flow Logs (network traffic)
# - DNS logs (domain lookups)
# - S3 data events
# - EKS audit logs
# Common GuardDuty findings:
# - Cryptocurrency mining on EC2
# - Compromised credentials (API calls from unusual location)
# - Unauthorized API calls
# - Port scanning from EC2 instance
# - Data exfiltration (S3 large data download to unusual IP)
# Get findings
aws guardduty list-findings --detector-id $DETECTOR_ID
aws guardduty get-findings \
--detector-id $DETECTOR_ID \
--finding-ids $FINDING_ID
# Auto-remediate with EventBridge + Lambda
# Finding → EventBridge rule → Lambda function → Isolate EC2 instance
aws events put-rule \
--name GuardDutyHighSeverity \
--event-pattern '{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": {
"severity": [{"numeric": [">=", 7]}]
}
}'

Q38: What is AWS Systems Manager (SSM) and how is it used in DevOps?

Section titled “Q38: What is AWS Systems Manager (SSM) and how is it used in DevOps?”

Answer: SSM is a management service for EC2 instances — patch management, remote access, automation.

Terminal window
# 1. Session Manager — SSH without key pairs or bastion host!
aws ssm start-session --target i-1234567890abcdef0
# 2. Run Command — run commands on multiple instances
aws ssm send-command \
--instance-ids i-1234 i-5678 \
--document-name AWS-RunShellScript \
--parameters commands=["apt-get update && apt-get upgrade -y"]
# 3. Patch Manager — automated patching
aws ssm create-patch-baseline \
--name "ProductionLinuxBaseline" \
--operating-system AMAZON_LINUX_2 \
--approval-rules \
PatchRules=[{
PatchFilterGroup={Filters=[{Key=CLASSIFICATION,Values=["SecurityUpdates"]},{Key=SEVERITY,Values=["Critical","Important"]}]},
ApproveAfterDays=7
}]
aws ssm create-maintenance-window \
--name "Sunday-2AM-Patching" \
--schedule "cron(0 2 ? * SUN *)" \
--duration 4 \
--cutoff 1
# 4. Parameter Store (already covered in Q30)
# 5. State Manager — ensure instances maintain desired state
# 6. Automation — automated runbooks for common tasks

Q39: How do you set up AWS CodeArtifact for dependency management?

Section titled “Q39: How do you set up AWS CodeArtifact for dependency management?”

Answer: CodeArtifact is a managed package repository for npm, pip, Maven packages.

Terminal window
# Create domain and repository
aws codeartifact create-domain --domain mycompany
aws codeartifact create-repository \
--domain mycompany \
--repository myapp-npm \
--description "Private npm packages"
# Connect public npm to upstream
aws codeartifact associate-external-connection \
--domain mycompany \
--repository myapp-npm \
--external-connection public:npmjs
# Authenticate npm
aws codeartifact login \
--tool npm \
--domain mycompany \
--repository myapp-npm
# Now npm uses CodeArtifact (with caching + private packages)
npm install react # Cached in CodeArtifact
# Publish private package
npm publish --registry https://mycompany.d.codeartifact.us-east-1.amazonaws.com/npm/myapp-npm/
# In CI/CD — authenticate before installing
- name: Configure CodeArtifact
run: |
aws codeartifact login --tool npm --domain mycompany --repository myapp-npm
npm ci # Uses CodeArtifact instead of public npm

Q40: What is AWS Elastic Beanstalk and when to use it?

Section titled “Q40: What is AWS Elastic Beanstalk and when to use it?”

Answer: Elastic Beanstalk is a PaaS — upload your code and AWS handles infrastructure.

Terminal window
# Initialize application
eb init myapp --platform node.js-18 --region us-east-1
# Create environment (deploys to EC2 + ALB + Auto Scaling)
eb create production \
--instance-type t3.medium \
--min-instances 2 \
--max-instances 10
# Deploy
eb deploy
# View status
eb status
eb health
# .ebextensions — configure environment
# .ebextensions/01-packages.config
packages:
yum:
git: []
nginx: []
files:
"/etc/nginx/conf.d/myapp.conf":
content: |
location /health {
return 200 'OK';
}
# When to use Beanstalk:
# ✅ Small teams, simple apps
# ✅ Don't want to manage infrastructure
# ✅ Quick prototypes
# ❌ Complex microservices
# ❌ Need fine-grained control
# ❌ Large enterprise deployments (use EKS/ECS)

Q41: How do you implement disaster recovery in AWS?

Section titled “Q41: How do you implement disaster recovery in AWS?”

Answer:

StrategyRTORPOCost
Backup & RestoreHoursHoursLow
Pilot Light~10 minMinutesMedium
Warm Standby~1 minSecondsHigh
Multi-Site Active-ActiveSeconds~0Very High
Terminal window
# Backup & Restore
# - Regular RDS snapshots to another region
aws rds create-db-snapshot \
--db-instance-identifier prod-db \
--db-snapshot-identifier prod-db-$(date +%Y%m%d)
# Copy snapshot to DR region
aws rds copy-db-snapshot \
--source-db-snapshot-identifier arn:aws:rds:us-east-1:123:snapshot/prod-db-20240115 \
--target-db-snapshot-identifier prod-db-dr-20240115 \
--region eu-west-1
# Pilot Light (minimal DR environment)
# - Minimal infrastructure always running in DR region
# - Scale up when disaster happens
# - RDS Multi-Region Read Replica
aws rds create-db-instance-read-replica \
--db-instance-identifier prod-db-dr \
--source-db-instance-identifier prod-db \
--region eu-west-1
# Route53 failover routing
# Health check on primary → automatic failover if unhealthy
aws route53 create-health-check \
--caller-reference hc-primary \
--health-check-config '{
"Type": "HTTPS",
"FullyQualifiedDomainName": "api.myapp.com",
"Port": 443,
"ResourcePath": "/health",
"FailureThreshold": 3
}'

Q42: What is AWS Inspector and how does it help security?

Section titled “Q42: What is AWS Inspector and how does it help security?”

Answer: Inspector automatically scans EC2 instances and container images for vulnerabilities.

Terminal window
# Enable Inspector v2
aws inspector2 enable \
--resource-types EC2 ECR LAMBDA
# Inspector scans:
# - EC2: OS vulnerabilities, network reachability
# - ECR: Container image vulnerabilities
# - Lambda: Function code vulnerabilities
# View findings
aws inspector2 list-findings \
--filter-criteria '{
"severity": [{"comparison":"EQUALS","value":"CRITICAL"}]
}'
# Get summary
aws inspector2 list-finding-aggregations \
--aggregation-type AWS_EC2_INSTANCE
# Suppress specific finding
aws inspector2 create-filter \
--action SUPPRESS \
--name "suppress-known-exception" \
--filter-criteria '{
"findingArn": [{"comparison":"EQUALS","value":"arn:aws:inspector2:..."}]
}'

Q43: How do you implement AWS Cost Allocation Tags?

Section titled “Q43: How do you implement AWS Cost Allocation Tags?”

Answer:

Terminal window
# Tag resources for cost tracking
aws ec2 create-tags \
--resources i-1234567890 \
--tags \
Key=Environment,Value=production \
Key=Team,Value=backend \
Key=Project,Value=myapp \
Key=CostCenter,Value=engineering
# Activate tags for cost allocation
aws ce update-cost-allocation-tags-status \
--cost-allocation-tags-status '[
{"TagKey": "Team", "Status": "Active"},
{"TagKey": "Environment", "Status": "Active"},
{"TagKey": "Project", "Status": "Active"}
]'
# View costs by team
aws ce get-cost-and-usage \
--time-period Start=2024-01-01,End=2024-01-31 \
--granularity MONTHLY \
--metrics BlendedCost \
--group-by Type=TAG,Key=Team
# Set budget alerts
aws budgets create-budget \
--account-id 123456789012 \
--budget '{
"BudgetName": "Monthly-Budget",
"BudgetLimit": {"Amount": "5000", "Unit": "USD"},
"TimeUnit": "MONTHLY",
"BudgetType": "COST",
"CostFilters": {"TagKeyValue": ["user:Team$backend"]}
}' \
--notifications-with-subscribers '[{
"Notification": {
"NotificationType": "ACTUAL",
"ComparisonOperator": "GREATER_THAN",
"Threshold": 80,
"ThresholdType": "PERCENTAGE"
},
"Subscribers": [{"SubscriptionType": "EMAIL","Address": "team@company.com"}]
}]'

Q44: What is AWS Step Functions and when to use it?

Section titled “Q44: What is AWS Step Functions and when to use it?”

Answer: Step Functions coordinates multiple Lambda functions into workflows (state machines).

// Order processing workflow
{
"Comment": "Order Processing",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...validate-order",
"Next": "ProcessPayment",
"Catch": [{
"ErrorEquals": ["ValidationError"],
"Next": "OrderFailed"
}]
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:...process-payment",
"Next": "CheckInventory",
"Retry": [{
"ErrorEquals": ["PaymentTimeout"],
"MaxAttempts": 3,
"IntervalSeconds": 5
}]
},
"CheckInventory": {
"Type": "Task",
"Resource": "arn:aws:lambda:...check-inventory",
"Next": "FulfillOrder"
},
"FulfillOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...fulfill-order",
"End": true
},
"OrderFailed": {
"Type": "Fail",
"Error": "OrderFailed"
}
}
}
Terminal window
# Start execution
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:...order-processing \
--input '{"orderId": "123", "amount": 99.99}'
# Get execution status
aws stepfunctions describe-execution \
--execution-arn arn:aws:states:...:execution/order-processing/abc123

Q45: How do you implement AWS EventBridge for event-driven architecture?

Section titled “Q45: How do you implement AWS EventBridge for event-driven architecture?”

Answer: EventBridge (formerly CloudWatch Events) routes events between AWS services and custom apps.

Terminal window
# Create custom event bus
aws events create-event-bus --name myapp-events
# Create rule — react to S3 upload
aws events put-rule \
--name ProcessImageUpload \
--event-bus-name myapp-events \
--event-pattern '{
"source": ["aws.s3"],
"detail-type": ["Object Created"],
"detail": {
"bucket": {"name": ["myapp-uploads"]},
"object": {"key": [{"suffix": ".jpg"}, {"suffix": ".png"}]}
}
}'
# Target — trigger Lambda on S3 upload
aws events put-targets \
--rule ProcessImageUpload \
--event-bus-name myapp-events \
--targets '[{
"Id": "ProcessImage",
"Arn": "arn:aws:lambda:...resize-image"
}]'
# Send custom event
aws events put-events \
--entries '[{
"EventBusName": "myapp-events",
"Source": "myapp.orders",
"DetailType": "OrderPlaced",
"Detail": "{\"orderId\":\"123\",\"userId\":\"456\"}"
}]'
# Scheduled rule — run every day at 2 AM
aws events put-rule \
--name DailyCleanup \
--schedule-expression "cron(0 2 * * ? *)"

Answer: Trusted Advisor analyzes your AWS account and gives recommendations across 5 categories.

5 Categories:
1. Cost Optimization
- Idle EC2 instances
- Underutilized EBS volumes
- Reserved Instance recommendations
2. Performance
- EC2 high utilization
- CloudFront optimization
- RDS provisioned IOPS
3. Security
- S3 bucket permissions (public?)
- IAM use
- MFA on root account
- Security group open access
4. Fault Tolerance
- RDS Multi-AZ
- Load balancer configuration
- Auto Scaling groups
- S3 versioning
5. Service Quotas
- Near quota limits
Terminal window
# Check Trusted Advisor findings
aws support describe-trusted-advisor-checks \
--language en
aws support describe-trusted-advisor-check-result \
--check-id pfx0RwqBli # S3 bucket permissions check
# Refresh check
aws support refresh-trusted-advisor-check \
--check-id pfx0RwqBli

Q47: How do you implement Blue-Green deployment with AWS CodeDeploy?

Section titled “Q47: How do you implement Blue-Green deployment with AWS CodeDeploy?”

Answer:

Terminal window
# Blue-Green with ECS (recommended)
aws deploy create-deployment-group \
--application-name myapp \
--deployment-group-name production \
--deployment-config-name CodeDeployDefault.ECSAllAtOnce \
--service-role-arn arn:aws:iam::...role/CodeDeployRole \
--ecs-services '[{
"serviceName": "myapp-service",
"clusterName": "production"
}]' \
--load-balancer-info '{
"targetGroupPairInfoList": [{
"targetGroups": [
{"name": "myapp-blue-tg"},
{"name": "myapp-green-tg"}
],
"prodTrafficRoute": {"listenerArns": ["arn:aws:elasticloadbalancing:..."]},
"testTrafficRoute": {"listenerArns": ["arn:aws:elasticloadbalancing:...test"]}
}]
}' \
--blue-green-deployment-configuration '{
"terminateBlueInstancesOnDeploymentSuccess": {
"action": "TERMINATE",
"terminationWaitTimeInMinutes": 5
},
"deploymentReadyOption": {
"actionOnTimeout": "STOP_DEPLOYMENT",
"waitTimeInMinutes": 30
}
}'

Q48: What is the difference between AWS Fargate and AWS Lambda?

Section titled “Q48: What is the difference between AWS Fargate and AWS Lambda?”

Answer:

FeatureLambdaFargate
RuntimeMax 15 minLong-running OK
Startup time~100ms cold start~30s container start
Max memory10GB120GB
BillingPer 100msPer vCPU/memory-second
Container supportVia container imageNative
Use caseEvent-driven, short tasksWeb servers, APIs, workers
VPCOptionalRequired for private
Concurrency1000 defaultAs many tasks as you want
Choose Lambda when:
- Event-driven (S3 upload, API Gateway, SQS)
- Short execution (<15 min)
- Variable/unpredictable traffic
- Rapid scaling needed
Choose Fargate when:
- Long-running services
- Existing Docker applications
- Need more than 10GB memory
- Complex multi-container apps

Q49: How do you implement AWS monitoring and alerting?

Section titled “Q49: How do you implement AWS monitoring and alerting?”

Answer:

Terminal window
# 1. CloudWatch metrics + alarms
aws cloudwatch put-metric-alarm \
--alarm-name HighCPU \
--alarm-description "Trigger when CPU > 80%" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--dimensions Name=AutoScalingGroupName,Value=myapp-asg \
--period 300 \
--evaluation-periods 2 \
--threshold 80 \
--comparison-operator GreaterThanThreshold \
--statistic Average \
--alarm-actions arn:aws:sns:...:alerts-topic \
--ok-actions arn:aws:sns:...:alerts-topic
# 2. Custom metric from application
aws cloudwatch put-metric-data \
--namespace MyApp \
--metric-name OrdersProcessed \
--value 1 \
--dimensions Environment=production
# 3. CloudWatch Dashboard
aws cloudwatch put-dashboard \
--dashboard-name MyApp-Production \
--dashboard-body '{
"widgets": [{
"type": "metric",
"properties": {
"metrics": [
["AWS/ECS","CPUUtilization","ClusterName","production"],
["AWS/ECS","MemoryUtilization","ClusterName","production"]
],
"period": 300,
"title": "ECS Cluster"
}
}]
}'
# 4. Container Insights (for ECS/EKS)
aws ecs update-cluster-settings \
--cluster production \
--settings name=containerInsights,value=enabled
# 5. Application Signals (new - auto-instrumentation)
aws application-signals enable-service-level-objectives

Q50: What is AWS Service Control Policies (SCP)?

Section titled “Q50: What is AWS Service Control Policies (SCP)?”

Answer: SCPs are organization-level policies that restrict what accounts in AWS Organizations can do — even admins.

// Prevent anyone from disabling CloudTrail
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"cloudtrail:DeleteTrail",
"cloudtrail:StopLogging",
"cloudtrail:UpdateTrail"
],
"Resource": "*"
},
{
"Effect": "Deny",
"Action": "ec2:*",
"Resource": "*",
"Condition": {
"StringNotEquals": {
"aws:RequestedRegion": ["us-east-1", "eu-west-1"]
}
}
}
]
}
Terminal window
# Apply SCP to Organizational Unit
aws organizations create-policy \
--name PreventCloudTrailDisable \
--type SERVICE_CONTROL_POLICY \
--content file://scp.json
aws organizations attach-policy \
--policy-id p-xxxx \
--target-id ou-yyyy # Organization Unit
# SCPs affect ALL accounts in the OU
# Even root user of member account can't override SCP
# Use for: Region restrictions, service restrictions, guardrails

Back to DevOps Q&A Index