AWS DevOps Interview Questions
AWS DevOps Interview Questions & Answers (1–50)
Section titled “AWS DevOps Interview Questions & Answers (1–50)”Section 1: AWS DevOps Core Services
Section titled “Section 1: AWS DevOps Core Services”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 DeployCodeCommit → CodeBuild → CodeBuild → CodeDeploy (EC2)GitHub → ECS (container)GitLab → EKS (kubernetes)Bitbucket → Elastic Beanstalk → LambdaPipeline 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" } }] } ] }}# Create pipeline via CLIaws codepipeline create-pipeline \ --cli-input-json file://pipeline.json
# Check pipeline statusaws codepipeline get-pipeline-state --name MyPipeline
# Manually triggeraws codepipeline start-pipeline-execution --name MyPipeline
# View execution historyaws codepipeline list-pipeline-executions --pipeline-name MyPipelineInterview 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.
Q2: What is AWS CodeBuild?
Section titled “Q2: What is AWS CodeBuild?”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:
| Strategy | What it does | Use case |
|---|---|---|
AllAtOnce | Deploy to all targets simultaneously | Dev/test (accepts downtime) |
HalfAtATime | Deploy to 50% at a time | Balance speed + safety |
OneAtATime | Deploy to one instance at a time | Max safety, slowest |
Custom | Define exact % (e.g., 25%) | Fine-grained control |
| ECS Linear | Shift 10% traffic every N minutes | Gradual canary |
| Lambda Canary | 10% for N minutes, then 100% | Lambda blue-green |
# appspec.yml for EC2 deploymentversion: 0.0os: linuxfiles: - source: /app destination: /opt/myapppermissions: - 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!# Create deploymentaws deploy create-deployment \ --application-name MyApp \ --deployment-group-name Production \ --deployment-config-name CodeDeployDefault.OneAtATime \ --github-location repository=org/repo,commitId=abc123
# Watch deployment statusaws deploy get-deployment --deployment-id d-XXXXXXXXX
# List deploymentsaws deploy list-deployments \ --application-name MyApp \ --deployment-group-name Production \ --include-only-statuses InProgress FailedInterview tip: CodeDeploy’s lifecycle hooks run in a specific order and if
ValidateServicescript exits with non-zero, CodeDeploy automatically rolls back. Always implement a real health check inValidateService(e.g.,curl http://localhost/health).
Section 2: AWS ECS & EKS
Section titled “Section 2: AWS ECS & EKS”Q4: What is the difference between ECS and EKS?
Section titled “Q4: What is the difference between ECS and EKS?”Answer:
| Aspect | ECS (Elastic Container Service) | EKS (Elastic Kubernetes Service) |
|---|---|---|
| Orchestrator | AWS-proprietary | Standard Kubernetes |
| Learning curve | Low (AWS-native concepts) | High (full K8s knowledge needed) |
| Control plane cost | Free | $0.10/hr (~$72/month) |
| Worker nodes | EC2 or Fargate | EC2 or Fargate |
| Ecosystem | AWS tools only | Full K8s ecosystem (Helm, Argo…) |
| Portability | AWS-locked | Portable (same YAML works anywhere) |
| Networking | AWS VPC CNI | Multiple CNI options |
| Auto-scaling | Service Auto Scaling + Fargate | HPA + Cluster Autoscaler + KEDA |
| Best for | AWS-first teams, simpler apps | K8s expertise, multi-cloud plans |
ECS concepts map to K8s:
ECS Task Definition ≠≡ K8s Pod specECS Task ≠≡ K8s PodECS Service ≠≡ K8s Deployment + ServiceECS Cluster ≠≡ K8s Node poolECR ≠≡ 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.”
Q5: How do you deploy to ECS using CI/CD?
Section titled “Q5: How do you deploy to ECS using CI/CD?”Answer:
# 1. Create ECR repositoryaws ecr create-repository --repository-name myapp
# 2. Build and push imageaws 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:$TAGdocker push $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/myapp:$TAG
# 3. Register new task definitionaws ecs register-task-definition \ --cli-input-json file://taskdef.json
# 4. Update serviceaws ecs update-service \ --cluster MyCluster \ --service MyService \ --task-definition myapp:$REVISION \ --force-new-deployment
# 5. Wait for deploymentaws 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"} ] }]}Q6: How do you set up EKS with CI/CD?
Section titled “Q6: How do you set up EKS with CI/CD?”Answer:
# Create EKS clustereksctl 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 kubeconfigaws 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/Section 3: AWS Infrastructure as Code
Section titled “Section 3: AWS Infrastructure as Code”Q7: What is CloudFormation and how does it work?
Section titled “Q7: What is CloudFormation and how does it work?”Answer:
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# Deploy stackaws cloudformation deploy \ --template-file cloudformation-stack.yaml \ --stack-name production-myapp \ --parameter-overrides Environment=production ImageTag=v1.2.0 \ --capabilities CAPABILITY_IAM
# View stack eventsaws cloudformation describe-stack-events \ --stack-name production-myapp
# Delete stackaws cloudformation delete-stack --stack-name production-myappQ8: How do you use AWS CDK for infrastructure?
Section titled “Q8: How do you use AWS CDK for infrastructure?”Answer:
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, }); }}# Deploy CDK stacknpm install -g aws-cdkcdk bootstrapcdk synth # Preview CloudFormationcdk diff # Show changescdk deploy # Deploycdk destroy # TeardownSection 4: AWS Monitoring & Observability
Section titled “Section 4: AWS Monitoring & Observability”Q9: How do you set up CloudWatch monitoring for applications?
Section titled “Q9: How do you set up CloudWatch monitoring for applications?”Answer:
# Create CloudWatch log groupaws logs create-log-group --log-group-name /myapp/production
# Set retentionaws logs put-retention-policy \ --log-group-name /myapp/production \ --retention-in-days 30
# Create metric filter for errorsaws 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 alarmaws 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:AlertTopicQ10: 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-Rayconst 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());# View X-Ray tracesaws xray get-trace-summaries \ --start-time $(date -d '1 hour ago' +%s) \ --end-time $(date +%s)Section 5: AWS Networking for DevOps
Section titled “Section 5: AWS Networking for DevOps”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:
# Create VPCaws 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-1aaws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.2.0/24 --availability-zone us-east-1b
# Create private subnetsaws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.10.0/24 --availability-zone us-east-1aaws ec2 create-subnet --vpc-id vpc-xxx --cidr-block 10.0.11.0/24 --availability-zone us-east-1b
# Internet Gateway for public subnetsaws ec2 create-internet-gatewayaws ec2 attach-internet-gateway --internet-gateway-id igw-xxx --vpc-id vpc-xxx
# NAT Gateway for private subnetsaws ec2 allocate-address --domain vpcaws ec2 create-nat-gateway --subnet-id subnet-public-1 --allocation-id eipalloc-xxxQ12: How do you set up Application Load Balancer with ECS?
Section titled “Q12: How do you set up Application Load Balancer with ECS?”Answer:
# Create ALBaws elbv2 create-load-balancer \ --name prod-alb \ --subnets subnet-pub-1 subnet-pub-2 \ --security-groups sg-alb \ --type application
# Create target groupaws 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 listeneraws 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:...Section 6: AWS Security for DevOps
Section titled “Section 6: AWS Security for DevOps”Q13: How do you manage secrets in AWS?
Section titled “Q13: How do you manage secrets in AWS?”Answer:
# AWS Secrets Manager (recommended)aws secretsmanager create-secret \ --name /production/db \ --secret-string '{"host":"db.internal","user":"app","password":"secret"}'
# Retrieve in applicationaws 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.ValueQ14: 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/*" } ]}# 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" } }}Section 7: AWS Lambda & Serverless DevOps
Section titled “Section 7: AWS Lambda & Serverless DevOps”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:
# Using AWS SAMsam buildsam 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.yamlAWSTemplateFormatVersion: '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: ANYBack to DevOps Q&A Index
Section 8: AWS Core Concepts for DevOps
Section titled “Section 8: AWS Core Concepts for DevOps”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:
| Concept | Description | Count (approx) |
|---|---|---|
| Region | Geographic area (e.g., us-east-1) | 33+ regions |
| Availability Zone (AZ) | Data center within a region | 2-6 per region |
| Edge Location | CloudFront CDN cache point | 400+ 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 availabilityBest practice: Deploy across 2+ regions for disaster recovery# List regionsaws ec2 describe-regions --output table
# List AZs in regionaws ec2 describe-availability-zones --region us-east-1Q17: What is the difference between EC2 instance types?
Section titled “Q17: What is the difference between EC2 instance types?”Answer:
| Family | Optimized for | Example | Use Case |
|---|---|---|---|
t3/t4g | Burstable performance | t3.medium | Dev, low traffic |
m6i | General purpose | m6i.xlarge | Web servers, APIs |
c6i | Compute-optimized | c6i.2xlarge | CPU-intensive, CI runners |
r6i | Memory-optimized | r6i.4xlarge | Databases, caching |
g4dn | GPU | g4dn.xlarge | ML, rendering |
i3 | Storage-optimized | i3.large | High I/O databases |
# Check instance pricingaws 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.jsonQ18: 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# Create Auto Scaling Groupaws 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:
| Feature | ALB (Application LB) | NLB (Network LB) |
|---|---|---|
| Layer | L7 (HTTP/HTTPS) | L4 (TCP/UDP) |
| Routing | Path, host, headers | IP, port |
| WebSocket | ✅ Yes | ✅ Yes |
| Latency | ~1ms extra | Ultra-low |
| Static IP | ❌ No | ✅ Yes |
| TLS termination | ✅ Yes | ✅ Yes |
| Use case | Web apps, microservices | Gaming, IoT, financial trading |
# ALB — content-based routingaws 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 serviceQ20: 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.
# DevOps use cases for S3:# 1. Static website hostingaws s3 website s3://myapp-frontend \ --index-document index.html \ --error-document 404.html
# 2. Store Terraform stateterraform { backend "s3" { bucket = "my-terraform-state" key = "production/terraform.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "terraform-lock" # State locking }}
# 3. Artifact storageaws s3 cp ./dist.tar.gz s3://artifacts/myapp/v1.5.0/dist.tar.gz
# 4. Log archivingaws s3 sync /var/log/myapp s3://logs-bucket/myapp/$(date +%Y/%m/%d)/
# 5. Backup storageaws 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} }] }'Q21: How does AWS IAM work?
Section titled “Q21: How does AWS IAM work?”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": "*" } ]}# 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 S3aws 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 permissionsaws iam simulate-principal-policy \ --policy-source-arn arn:aws:iam::123456789012:role/MyRole \ --action-names s3:GetObjectPrinciple 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.
# 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 VPCVPC_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 DNSaws ec2 modify-vpc-attribute --vpc-id $VPC_ID \ --enable-dns-hostnames
# Create subnets (2 AZs for HA)# Public subnetsaws ec2 create-subnet --vpc-id $VPC_ID \ --cidr-block 10.0.1.0/24 --availability-zone us-east-1aaws 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-1aaws 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-1aaws 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 $EIPQ23: What are Security Groups vs NACLs?
Section titled “Q23: What are Security Groups vs NACLs?”Answer:
| Feature | Security Group | NACL |
|---|---|---|
| Level | Instance level | Subnet level |
| State | Stateful | Stateless |
| Rules | Allow only | Allow and Deny |
| Default | Deny all in, allow all out | Allow all |
| Evaluation | All rules evaluated | Rules in number order |
# Security Group — attached to instances# Stateful: If you allow inbound 80, response is auto-allowed outbound
# Create web server security groupaws ec2 create-security-group \ --group-name web-sg \ --description "Web servers" \ --vpc-id $VPC_ID
# Allow inbound HTTP from ALB security group onlyaws 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 outboundaws 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 \ --ingressQ24: 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.
# 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-dbQ25: 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.
# Create hosted zoneaws route53 create-hosted-zone \ --name myapp.com \ --caller-reference $(date +%s)
# Simple A recordaws 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 v2aws 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 unhealthyQ26: 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.
# 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 alertsaws logs put-metric-filter \ --log-group-name CloudTrail/DefaultLogGroup \ --filter-name RootAccountUsage \ --filter-pattern '{ $.userIdentity.type = "Root" }' \ --metric-transformations metricName=RootAccountUsage,metricNamespace=Security,metricValue=1Q27: 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.
# AWS Config tracks:# - Current state of all AWS resources# - Historical configuration changes# - Relationships between resources
# Enable AWS Configaws 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 checksaws configservice put-config-rule \ --config-rule '{ "ConfigRuleName": "s3-bucket-public-read-prohibited", "Source": { "Owner": "AWS", "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED" } }'
# Check complianceaws 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-accessQ28: What is AWS SQS vs SNS?
Section titled “Q28: What is AWS SQS vs SNS?”Answer:
| Feature | SQS (Queue) | SNS (Topic) |
|---|---|---|
| Type | Pull-based queue | Push-based pub/sub |
| Consumers | One consumer per message | Multiple subscribers |
| Persistence | Messages stored until consumed | Messages not stored |
| Pattern | Task queues, worker pools | Fan-out, notifications |
| Example | Process orders | Notify all services of new order |
# SQS — Order processing queue# Producer sends order → SQS Queue → Worker pulls and processes
# Create SQS queueaws sqs create-queue \ --queue-name orders-queue \ --attributes '{ "VisibilityTimeout": "30", "MessageRetentionPeriod": "86400", "ReceiveMessageWaitTimeSeconds": "20" }'
# Send messageaws sqs send-message \ --queue-url https://sqs.us-east-1.amazonaws.com/123/orders-queue \ --message-body '{"orderId": "123", "amount": 99.99}'
# Receive and processaws 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 arrivesaws sns create-topic --name order-events
# Subscribe SQS queue to SNS topicaws 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 itaws 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.
# Common WAF use cases:# - Block SQL injection# - Block XSS# - Rate limiting (DDoS protection)# - Geo-blocking# - Block known malicious IPs
# Create WAF WebACLaws 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 ALBaws 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:
| Feature | Secrets Manager | SSM Parameter Store |
|---|---|---|
| Cost | $0.40/secret/month | Free (Standard tier) |
| Auto-rotation | ✅ Built-in | ❌ Manual (with Lambda) |
| Cross-account | ✅ Yes | ❌ No |
| Size limit | 65KB | 4KB (Standard), 8KB (Advanced) |
| Use for | DB passwords, API keys | Config values, feature flags |
# Secrets Manager — for sensitive secrets with rotationaws 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 configurationaws 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 applicationaws secretsmanager get-secret-value --secret-id /production/databaseaws ssm get-parameter --name /production/app/api-key --with-decryptionQ31: 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.
# Create CloudFront distribution for S3 static siteaws 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 deploymentaws 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.
# Create KMS keyaws 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 dataaws kms encrypt \ --key-id alias/prod-app-key \ --plaintext "my-sensitive-data" \ --output text --query CiphertextBlob | base64 -d > encrypted.bin
# Decrypt dataaws 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.
# 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 functionaws 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 Lambdaaws 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 serversQ34: What is AWS ECS Fargate vs EC2 launch type?
Section titled “Q34: What is AWS ECS Fargate vs EC2 launch type?”Answer:
| Feature | ECS Fargate | ECS EC2 |
|---|---|---|
| Server management | ❌ None | ✅ You manage |
| Cost | Higher per vCPU/memory | Lower if right-sized |
| Scaling | Fast (no instance warmup) | Slower (EC2 launch time) |
| Control | Limited | Full OS access |
| Best for | Most containerized apps | GPU, custom AMI needs |
# Fargate task — no EC2 managementaws 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:
# 1. Right-sizing — find oversized instancesaws ce get-rightsizing-recommendation \ --service EC2
# 2. Reserved Instances — save 40-60% vs On-Demandaws 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 interruptedaws ec2 request-spot-fleet \ --spot-fleet-request-config '{ "IamFleetRole": "arn:aws:iam::...role/spot-fleet", "AllocationStrategy": "diversified", "TargetCapacity": 10, "LaunchSpecifications": [...] }'
# 5. S3 Intelligent-Tieringaws 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 wasteaws 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 resourcesaws 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 selfQ36: 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.
# Create ECR repositoryaws ecr create-repository \ --repository-name myapp \ --image-scanning-configuration scanOnPush=true \ --encryption-configuration encryptionType=KMS \ --image-tag-mutability IMMUTABLE
# Authenticate Docker to ECRaws 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 imagedocker build -t myapp:1.0 .docker tag myapp:1.0 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:1.0docker 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 resultsaws ecr describe-image-scan-findings \ --repository-name myapp \ --image-id imageTag=1.0Q37: 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.
# Enable GuardDutyaws 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 findingsaws guardduty list-findings --detector-id $DETECTOR_IDaws guardduty get-findings \ --detector-id $DETECTOR_ID \ --finding-ids $FINDING_ID
# Auto-remediate with EventBridge + Lambda# Finding → EventBridge rule → Lambda function → Isolate EC2 instanceaws 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.
# 1. Session Manager — SSH without key pairs or bastion host!aws ssm start-session --target i-1234567890abcdef0
# 2. Run Command — run commands on multiple instancesaws 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 patchingaws 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 tasksQ39: 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.
# Create domain and repositoryaws codeartifact create-domain --domain mycompany
aws codeartifact create-repository \ --domain mycompany \ --repository myapp-npm \ --description "Private npm packages"
# Connect public npm to upstreamaws codeartifact associate-external-connection \ --domain mycompany \ --repository myapp-npm \ --external-connection public:npmjs
# Authenticate npmaws 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 packagenpm 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 npmQ40: 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.
# Initialize applicationeb 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
# Deployeb deploy
# View statuseb statuseb health
# .ebextensions — configure environment# .ebextensions/01-packages.configpackages: 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:
| Strategy | RTO | RPO | Cost |
|---|---|---|---|
| Backup & Restore | Hours | Hours | Low |
| Pilot Light | ~10 min | Minutes | Medium |
| Warm Standby | ~1 min | Seconds | High |
| Multi-Site Active-Active | Seconds | ~0 | Very High |
# Backup & Restore# - Regular RDS snapshots to another regionaws rds create-db-snapshot \ --db-instance-identifier prod-db \ --db-snapshot-identifier prod-db-$(date +%Y%m%d)
# Copy snapshot to DR regionaws 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 Replicaaws 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 unhealthyaws 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.
# Enable Inspector v2aws inspector2 enable \ --resource-types EC2 ECR LAMBDA
# Inspector scans:# - EC2: OS vulnerabilities, network reachability# - ECR: Container image vulnerabilities# - Lambda: Function code vulnerabilities
# View findingsaws inspector2 list-findings \ --filter-criteria '{ "severity": [{"comparison":"EQUALS","value":"CRITICAL"}] }'
# Get summaryaws inspector2 list-finding-aggregations \ --aggregation-type AWS_EC2_INSTANCE
# Suppress specific findingaws 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:
# Tag resources for cost trackingaws 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 allocationaws 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 teamaws 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 alertsaws 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" } }}# Start executionaws stepfunctions start-execution \ --state-machine-arn arn:aws:states:...order-processing \ --input '{"orderId": "123", "amount": 99.99}'
# Get execution statusaws stepfunctions describe-execution \ --execution-arn arn:aws:states:...:execution/order-processing/abc123Q45: 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.
# Create custom event busaws events create-event-bus --name myapp-events
# Create rule — react to S3 uploadaws 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 uploadaws events put-targets \ --rule ProcessImageUpload \ --event-bus-name myapp-events \ --targets '[{ "Id": "ProcessImage", "Arn": "arn:aws:lambda:...resize-image" }]'
# Send custom eventaws events put-events \ --entries '[{ "EventBusName": "myapp-events", "Source": "myapp.orders", "DetailType": "OrderPlaced", "Detail": "{\"orderId\":\"123\",\"userId\":\"456\"}" }]'
# Scheduled rule — run every day at 2 AMaws events put-rule \ --name DailyCleanup \ --schedule-expression "cron(0 2 * * ? *)"Q46: What is AWS Trusted Advisor?
Section titled “Q46: What is AWS Trusted Advisor?”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# Check Trusted Advisor findingsaws support describe-trusted-advisor-checks \ --language en
aws support describe-trusted-advisor-check-result \ --check-id pfx0RwqBli # S3 bucket permissions check
# Refresh checkaws support refresh-trusted-advisor-check \ --check-id pfx0RwqBliQ47: How do you implement Blue-Green deployment with AWS CodeDeploy?
Section titled “Q47: How do you implement Blue-Green deployment with AWS CodeDeploy?”Answer:
# 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:
| Feature | Lambda | Fargate |
|---|---|---|
| Runtime | Max 15 min | Long-running OK |
| Startup time | ~100ms cold start | ~30s container start |
| Max memory | 10GB | 120GB |
| Billing | Per 100ms | Per vCPU/memory-second |
| Container support | Via container image | Native |
| Use case | Event-driven, short tasks | Web servers, APIs, workers |
| VPC | Optional | Required for private |
| Concurrency | 1000 default | As 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 appsQ49: How do you implement AWS monitoring and alerting?
Section titled “Q49: How do you implement AWS monitoring and alerting?”Answer:
# 1. CloudWatch metrics + alarmsaws 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 applicationaws cloudwatch put-metric-data \ --namespace MyApp \ --metric-name OrdersProcessed \ --value 1 \ --dimensions Environment=production
# 3. CloudWatch Dashboardaws 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-objectivesQ50: 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"] } } } ]}# Apply SCP to Organizational Unitaws 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, guardrailsBack to DevOps Q&A Index