AWS_Practical_Interview_101 200
AWS Practical Interview Questions (101-200)
Section titled “AWS Practical Interview Questions (101-200)”CloudFront and CDN
Section titled “CloudFront and CDN”Q101: How do you create CloudFront distribution?
Section titled “Q101: How do you create CloudFront distribution?”Answer:
# Create distributionaws cloudfront create-distribution \ --origin-domain-name mybucket.s3.amazonaws.com \ --default-root-object index.html \ --enabled \ --price-class PriceClass_AllQ102: How do you set up CloudFront with S3?
Section titled “Q102: How do you set up CloudFront with S3?”Answer:
# Create OAIaws cloudfront create-cloud-front-origin-access-identity \ --cloud-front-origin-access-identity-config CallerReference="my-oai",Comment="OAI for S3"
# Update S3 bucket policyaws s3api put-bucket-policy \ --bucket my-bucket \ --policy '{ "Version": "2008-10-17", "Statement": [{ "Sid": "Allow CloudFront OAI", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1234567890ABC"}, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*" }] }'Q103: How do you create signed URL for CloudFront?
Section titled “Q103: How do you create signed URL for CloudFront?”Answer:
import boto3import datetime
cloudfront = boto3.client('cloudfront')
# Create signed URLurl = cloudfront.generate_signed_url( url='https://d1234567890.cloudfront.net/private/content.mp4', policy='{"Statement":[{"Resource":"https://d1234567890.cloudfront.net/private/*","Condition":{"DateLessThan":{"AWS:EpochTime":' + str(int((datetime.datetime.now() + datetime.timedelta(hours=1)).timestamp())) + '}}}]}', key_pair_id='K1234567890ABC', private_key_file='private_key.pem')print(url)Q104: How do you invalidate CloudFront cache?
Section titled “Q104: How do you invalidate CloudFront cache?”Answer:
# Invalidate all filesaws cloudfront create-invalidation \ --distribution-id E1234567890ABC \ --paths "/*"
# Invalidate specific filesaws cloudfront create-invalidation \ --distribution-id E1234567890ABC \ --paths "/index.html" "/images/*.jpg"EFS and File Storage
Section titled “EFS and File Storage”Q105: How do you create EFS file system?
Section titled “Q105: How do you create EFS file system?”Answer:
# Create EFSaws efs create-file-system \ --throughput-mode bursting \ --encrypted \ --performance-mode generalPurpose
# Create mount targetaws efs create-mount-target \ --file-system-id fs-1234567890abcdef0 \ --subnet-id subnet-12345 \ --security-groups sg-12345Q106: How do you mount EFS on EC2?
Section titled “Q106: How do you mount EFS on EC2?”Answer:
# Install EFS utilssudo yum install -y amazon-efs-utils
# Mount EFSsudo mount -t efs fs-1234567890abcdef0:/ /mnt/efs
# Mount with TLSsudo mount -t efs -o tls fs-1234567890abcdef0:/ /mnt/efsQ107: How do you create FSx file system?
Section titled “Q107: How do you create FSx file system?”Answer:
# Create FSx for Windowsaws fsx create-file-system \ --file-system-type WINDOWS \ --storage-capacity 300 \ --subnet-ids subnet-12345 \ --windows-configuration '{ "ReplicationSpecification": {"SecondaryBackupRegion": "us-west-2"}, "ThroughputCapacity": 8, "PreferredSubnetId": "subnet-12345" }'Database Deep Dive
Section titled “Database Deep Dive”Q108: How do you connect to RDS using SSL?
Section titled “Q108: How do you connect to RDS using SSL?”Answer:
# Download SSL certificatewget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
# Connect with SSLmysql -h mydb.xxxx.rds.amazonaws.com \ -u admin -p \ --ssl-ca=rds-combined-ca-bundle.pem \ --ssl-mode=REQUIREDQ109: How do you change RDS instance class?
Section titled “Q109: How do you change RDS instance class?”Answer:
# Modify RDS instanceaws rds modify-db-instance \ --db-instance-identifier mydb \ --db-instance-class db.t3.medium \ --apply-immediately
# Or for planned maintenance windowaws rds modify-db-instance \ --db-instance-identifier mydb \ --db-instance-class db.t3.medium \ --apply-during-maintenance-windowQ110: How do you enable RDS performance insights?
Section titled “Q110: How do you enable RDS performance insights?”Answer:
# Enable Performance Insightsaws rds create-performance-insights-encryption-default \ --aws-region us-east-1
# Or on instanceaws rds modify-db-instance \ --db-instance-identifier mydb \ --enable-performance-insights \ --performance-insights-kms-key-id key-idQ111: How do you restore RDS from S3?
Section titled “Q111: How do you restore RDS from S3?”Answer:
# Restore MySQL from S3aws rds restore-db-instance-from-s3 \ --db-instance-identifier mydb \ --s3-bucket-name my-backup-bucket \ --s3-prefix backups/ \ --s3-ingestion-role-arn arn:aws:iam::123456789012:role/rds-s3-role \ --engine mysql \ --master-username admin \ --master-user-password mypassword123 \ --allocated-storage 100Q112: How do you configure RDS parameter group?
Section titled “Q112: How do you configure RDS parameter group?”Answer:
# Create parameter groupaws rds create-db-parameter-group \ --db-parameter-group-name my-param-group \ --db-parameter-group-family mysql8.0 \ --description "Custom parameter group"
# Modify parameteraws rds modify-db-parameter-group \ --db-parameter-group-name my-param-group \ --parameters '[ {"ParameterName":"max_connections","Value":"200","ApplyMethod":"immediate"} ]'Q113: How do you create DynamoDB table with TTL?
Section titled “Q113: How do you create DynamoDB table with TTL?”Answer:
aws dynamodb create-table \ --table-name Orders \ --attribute-definitions AttributeName=OrderID,AttributeType=S \ --key-schema AttributeName=OrderID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST
# Enable TTLaws dynamodb update-time-to-live \ --table-name Orders \ --time-to-live-specification Enabled=true,AttributeName=TTLVPC and Networking Deep Dive
Section titled “VPC and Networking Deep Dive”Q114: How do you create VPC endpoint for S3?
Section titled “Q114: How do you create VPC endpoint for S3?”Answer:
# Create endpointaws ec2 create-vpc-endpoint \ --vpc-id vpc-1234567890abcdef0 \ --service-name com.amazonaws.us-east-1.s3 \ --route-table-ids rtb-12345
# Use VPC endpoint in S3 access# No additional config needed - private access to S3Q115: How do you create VPC endpoint for DynamoDB?
Section titled “Q115: How do you create VPC endpoint for DynamoDB?”Answer:
# Create endpointaws ec2 create-vpc-endpoint \ --vpc-id vpc-1234567890abcdef0 \ --service-name com.amazonaws.us-east-1.dynamodb \ --route-table-ids rtb-12345Q116: How do you set up PrivateLink (interface endpoint)?
Section titled “Q116: How do you set up PrivateLink (interface endpoint)?”Answer:
# Create interface endpointaws ec2 create-vpc-endpoint \ --vpc-id vpc-1234567890abcdef0 \ --service-name com.amazonaws.us-east-1.ec2 \ --vpc-endpoint-type Interface \ --subnet-ids subnet-12345 subnet-67890Q117: How do you configure VPC DNS options?
Section titled “Q117: How do you configure VPC DNS options?”Answer:
# Enable DNS hostnameaws ec2 modify-vpc-attribute \ --vpc-id vpc-1234567890abcdef0 \ --enable-dns-hostnames "{\"Value\":true}"
# Enable DNS supportaws ec2 modify-vpc-attribute \ --vpc-id vpc-1234567890abcdef0 \ --enable-dns-support "{\"Value\":true}"Q118: How do you create custom VPC with public and private subnets?
Section titled “Q118: How do you create custom VPC with public and private subnets?”Answer:
# Create VPCVPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query 'Vpc.VpcId' --output text)
# Create public subnetPUBLIC_SUBNET=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.1.0/24 --availability-zone us-east-1a --query 'Subnet.SubnetId' --output text)
# Create private subnetPRIVATE_SUBNET=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.2.0/24 --availability-zone us-east-1a --query 'Subnet.SubnetId' --output text)
# Create and attach IGWIGW_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
# Create public route tableROUTE_TABLE=$(aws ec2 create-route-table --vpc-id $VPC_ID --query 'RouteTable.RouteTableId' --output text)aws ec2 create-route --route-table-id $ROUTE_TABLE --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW_IDaws ec2 associate-route-table --route-table-id $ROUTE_TABLE --subnet-id $PUBLIC_SUBNETLambda Advanced
Section titled “Lambda Advanced”Q119: How do you set up Lambda destination?
Section titled “Q119: How do you set up Lambda destination?”Answer:
# Configure destination for successaws lambda put-function-event-invoke-config \ --function-name my-function \ --destination-config '{ "OnSuccess": {"Destination": "arn:aws:sqs:us-east-1:123456789012:success-queue"}, "OnFailure": {"Destination": "arn:aws:sqs:us-east-1:123456789012:failed-queue"} }'Q120: How do you use Lambda SnapStart?
Section titled “Q120: How do you use Lambda SnapStart?”Answer:
# Enable SnapStart for Java functionsaws lambda update-function-configuration \ --function-name my-java-function \ --snap-start '{"ApplyOn":"PublishedVersions"}'
# Publish versionaws lambda publish-version --function-name my-java-functionQ121: How do you configure reserved concurrency?
Section titled “Q121: How do you configure reserved concurrency?”Answer:
# Set reserved concurrencyaws lambda put-function-concurrency \ --function-name my-function \ --reserved-concurrent-executions 10
# Remove reserved concurrencyaws lambda delete-function-concurrency --function-name my-functionQ122: How do you set up provisioned concurrency?
Section titled “Q122: How do you set up provisioned concurrency?”Answer:
# Configure provisioned concurrencyaws lambda put-provisioned-concurrency-config \ --function-name my-function \ --qualifier 5 \ --provisioned-concurrent-executions 5Q123: How do you use Lambda layers?
Section titled “Q123: How do you use Lambda layers?”Answer:
# Create layeraws lambda publish-layer-version \ --layer-name my-layer \ --description "Pandas for data processing" \ --zip-file fileb://layer.zip \ --compatible-runtimes python3.9
# Add to functionaws lambda update-function-configuration \ --function-name my-function \ --layers arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1API Gateway Advanced
Section titled “API Gateway Advanced”Q124: How do you create API Gateway REST API?
Section titled “Q124: How do you create API Gateway REST API?”Answer:
# Create APIAPI_ID=$(aws apigateway create-rest-api \ --name my-api \ --query 'id' \ --output text)
# Get root resourceROOT_ID=$(aws apigateway get-resources \ --rest-api-id $API_ID \ --query 'items[0].id' \ --output text)
# Create resourceRESOURCE_ID=$(aws apigateway create-resource \ --rest-api-id $API_ID \ --parent-id $ROOT_ID \ --path-part users \ --query 'id' \ --output text)Q125: How do to create API Gateway method?
Section titled “Q125: How do to create API Gateway method?”Answer:
# Create GET methodaws apigateway put-method \ --rest-api-id $API_ID \ --resource-id $RESOURCE_ID \ --http-method GET \ --authorization-type NONE
# Create POST method with Lambda integrationaws apigateway put-integration \ --rest-api-id $API_ID \ --resource-id $RESOURCE_ID \ --http-method POST \ --type AWS \ --integration-http-method POST \ --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:my-function/invocationsQ126: How do you set up API Gateway usage plan?
Section titled “Q126: How do you set up API Gateway usage plan?”Answer:
# Create usage planaws apigateway create-usage-plan \ --name my-usage-plan \ --api-stages apiId=abc123,stage=prod \ --quota '{"Limit":10000,"Period":"MONTH"}' \ --throttle '{"BurstLimit":100,"RateLimit":50}'Q127: How do you create API key?
Section titled “Q127: How do you create API key?”Answer:
# Create API keyaws apigateway create-api-key \ --name my-api-key \ --enabled
# Add to usage planaws apigateway create-usage-plan-key \ --usage-plan-id abc123 \ --key-id xyz789 \ --key-type API_KEYQ128: How do you configure API Gateway caching?
Section titled “Q128: How do you configure API Gateway caching?”Answer:
# Enable caching on stageaws apigateway update-stage \ --rest-api-id $API_ID \ --stage-name prod \ --patch-operations '[{"op":"replace","path":"/*/settings/cacheEnabled","value":"true"}]'
# Set cache ttlaws apigateway update-stage \ --rest-api-id $API_ID \ --stage-name prod \ --patch-operations '[{"op":"replace","path":"/*/settings/cacheTtlInSeconds","value":"300"}]'CloudWatch Advanced
Section titled “CloudWatch Advanced”Q129: How do you create custom CloudWatch metric?
Section titled “Q129: How do you create custom CloudWatch metric?”Answer:
import boto3
cloudwatch = boto3.client('cloudwatch')
# Put metric datacloudwatch.put_metric_data( Namespace='MyApplication', MetricData=[ { 'MetricName': 'RequestCount', 'Value': 1, 'Unit': 'Count', 'Dimensions': [ {'Name': 'ServiceName', 'Value': 'MyService'}, {'Name': 'Environment', 'Value': 'Production'} ] } ])Q130: How do you create CloudWatch alarm with SNS?
Section titled “Q130: How do you create CloudWatch alarm with SNS?”Answer:
# Create topicTOPIC_ARN=$(aws sns create-topic --name cpu-alarm --query 'TopicArn' --output text)
# Subscribe emailaws sns subscribe \ --topic-arn $TOPIC_ARN \ --protocol email \ --notification-endpoint admin@example.com
# Create alarmaws cloudwatch put-metric-alarm \ --alarm-name cpu-alarm \ --alarm-description "CPU usage above 80%" \ --metric-name CPUUtilization \ --namespace AWS/EC2 \ --statistic Average \ --period 300 \ --threshold 80 \ --comparison-operator GreaterThanThreshold \ --evaluation-periods 2 \ --alarm-actions $TOPIC_ARNQ131: How do you create CloudWatch composite alarm?
Section titled “Q131: How do you create CloudWatch composite alarm?”Answer:
aws cloudwatch put-composite-alarm \ --alarm-name composite-alarm \ --alarm-rule "(ALARM cpu-alarm OR ALARM memory-alarm) AND (ALARM disk-alarm)" \ --alarm-actions arn:aws:sns:us-east-1:123456789012:my-topicCloudFormation Advanced
Section titled “CloudFormation Advanced”Q132: How do you use CloudFormation Condition functions?
Section titled “Q132: How do you use CloudFormation Condition functions?”Answer:
AWSTemplateFormatVersion: '2010-09-09'Description: Conditions Example
Parameters: Environment: Type: String Default: dev AllowedValues: - dev - prod
Conditions: IsProduction: !Equals [!Ref Environment, prod] UseEncryptedStorage: !Equals [!Ref Environment, prod]
Resources: MyInstance: Type: AWS::EC2::Instance Properties: ImageId: !Ref LatestAmiId InstanceType: !If [IsProduction, t3.large, t3.micro] Encrypted: !Ref UseEncryptedStorageQ133: How do you use CloudFormation DependsOn?
Section titled “Q133: How do you use CloudFormation DependsOn?”Answer:
Resources: DbSubnetGroup: Type: AWS::RDS::DBSubnetGroup Properties: DBSubnetGroupName: my-subnet-group DBSubnetDescriptions: - !Ref PrivateSubnet1 - !Ref PrivateSubnet2
MyDatabase: Type: AWS::RDS::DBInstance DependsOn: DbSubnetGroup Properties: DBInstanceClass: db.t3.micro Engine: mysqlQ134: How do you use CloudFormation DeletionPolicy?
Section titled “Q134: How do you use CloudFormation DeletionPolicy?”Answer:
Resources: MyVolume: Type: AWS::EC2::Volume DeletionPolicy: Snapshot Properties: Size: 100 AvailabilityZone: us-east-1a
MyDatabase: Type: AWS::RDS::DBInstance DeletionPolicy: Snapshot Properties: DBInstanceClass: db.t3.microQ135: How do you use CloudFormation WaitCondition?
Section titled “Q135: How do you use CloudFormation WaitCondition?”Answer:
Resources: WaitHandle: Type: AWS::CloudFormation::WaitConditionHandle Properties: Timeout: PT15M
WaitCondition: Type: AWS::CloudFormation::WaitCondition DependsOn: MyInstance Properties: Handle: !Ref WaitHandle Timeout: PT15M Count: 1Q136: How do you use CloudFormation Custom Resource?
Section titled “Q136: How do you use CloudFormation Custom Resource?”Answer:
Resources: CustomResource: Type: AWS::CloudFormation::CustomResource Properties: ServiceToken: !GetAtt MyFunction.Arn Key: Value
MyFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.9 Handler: index.handler Code: ZipFile: | import boto3 import json def handler(event, context): return {'Status': 'SUCCESS'}ECS Advanced
Section titled “ECS Advanced”Q137: How do you update ECS service?
Section titled “Q137: How do you update ECS service?”Answer:
# Update serviceaws ecs update-service \ --cluster my-cluster \ --service my-service \ --task-definition my-app:2 \ --desired-count 5 \ --deployment-configuration minimumHealthyPercent=50,maximumPercent=200
# Force new deploymentaws ecs update-service \ --cluster my-cluster \ --service my-service \ --force-new-deploymentQ138: How do you create ECS task placement strategy?
Section titled “Q138: How do you create ECS task placement strategy?”Answer:
{ "cluster": "my-cluster", "service": "my-service", "taskDefinition": "my-app:1", "launchType": "FARGATE", "platformVersion": "LATEST", "networkConfiguration": { "awsvpcConfiguration": { "subnets": ["subnet-12345"], "securityGroups": ["sg-12345"] } }, "placementStrategy": [ { "type": "spread", "field": "attribute:ecs.availability-zone" }, { "type": "binpack", "field": "cpu" } ]}Q139: How do you set up ECS service discovery?
Section titled “Q139: How do you set up ECS service discovery?”Answer:
# Create namespaceaws servicediscovery create-private-dns-namespace \ --name local \ --vpc vpc-1234567890abcdef0
# Create service with discoveryaws servicediscovery create-service \ --name my-service \ --namespace-id ns-12345 \ --dns-config '{ "NamespaceId": "ns-12345", "DnsRecords": [{"Type": "A", "TTL": 60}] }' \ --health-check-config '{"Type": "HTTP", "ResourcePath": "/health"}'SQS and SNS Advanced
Section titled “SQS and SNS Advanced”Q140: How do you set up SNS FIFO topic?
Section titled “Q140: How do you set up SNS FIFO topic?”Answer:
# Create FIFO topicaws sns create-topic \ --name my-fifo-topic.fifo \ --attributes '{ "FifoTopic": "true", "ContentBasedDeduplication": "true" }'
# Subscribe SQS to SNSaws sns subscribe \ --topic-arn arn:aws:sns:us-east-1:123456789012:my-fifo-topic.fifo \ --protocol sqs \ --notification-endpoint arn:aws:sqs:us-east-1:123456789012:my-queue.fifoQ141: How do you configure SQS dead letter queue?
Section titled “Q141: How do you configure SQS dead letter queue?”Answer:
# Create DLQaws sqs create-queue \ --queue-name my-dlq.fifo \ --attributes '{"FifoQueue":"true","ContentBasedDeduplication":"true"}'
# Create main queue with DLQaws sqs create-queue \ --queue-name my-queue.fifo \ --attributes '{ "FifoQueue": "true", "ContentBasedDeduplication": "true", "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:123456789012:my-dlq.fifo\",\"maxReceiveCount\":5}" }'Q142: How do you set up SQS message attributes?
Section titled “Q142: How do you set up SQS message attributes?”Answer:
# Send message with attributesaws sqs send-message \ --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue \ --message-body '{"orderId": "123"}' \ --message-attributes '{ "CustomerId": {"DataType": "String", "StringValue": "C123"}, "OrderValue": {"DataType": Number, "StringValue": "99.99"} }'Kinesis
Section titled “Kinesis”Q143: How do you create Kinesis stream?
Section titled “Q143: How do you create Kinesis stream?”Answer:
# Create streamaws kinesis create-stream \ --stream-name my-stream \ --shard-count 2
# Describe streamaws kinesis describe-stream-summary \ --stream-name my-stream
# List streamsaws kinesis list-streamsQ144: How do you put record in Kinesis?
Section titled “Q144: How do you put record in Kinesis?”Answer:
# Put recordaws kinesis put-record \ --stream-name my-stream \ --partition-key user123 \ --data $(echo '{"event": "click", "page": "home"}' | base64)
# Put records (batch)aws kinesis put-records \ --stream-name my-stream \ --records '[{"PartitionKey":"user1","Data":"ZWNobyB0ZXN0"},{"PartitionKey":"user2","Data":"ZWNobyB0ZXN0Mg=="}]'Q145: How do you read from Kinesis?
Section titled “Q145: How do you read from Kinesis?”Answer:
# Get iteratorSHARD_ITERATOR=$(aws kinesis get-shard-iterator \ --stream-name my-stream \ --shard-id shardId-000000000000 \ --shard-iterator-type LATEST \ --query 'ShardIterator' \ --output text)
# Get recordsaws kinesis get-records \ --shard-iterator $SHARD_ITERATORSystems Manager
Section titled “Systems Manager”Q146: How do you run command on EC2 using SSM?
Section titled “Q146: How do you run command on EC2 using SSM?”Answer:
# Send commandaws ssm send-command \ --document-name AWS-RunShellScript \ --targets '[{"Key":"InstanceIds","Values":["i-1234567890abcdef0"]}]' \ --parameters '{ "commands":["#!/bin/bash","yum update -y","yum install -y httpd"], "executionTimeout":["3600"] }'
# Check command statusaws ssm list-command-invocations \ --command-id command-idQ147: How do you create SSM parameter?
Section titled “Q147: How do you create SSM parameter?”Answer:
# Create parameteraws ssm put-parameter \ --name /myapp/database/host \ --value mydb.xxx.rds.amazonaws.com \ --type String
# Create secure stringaws ssm put-parameter \ --name /myapp/database/password \ --value mypassword123 \ --type SecureString
# Get parameteraws ssm get-parameter --name /myapp/database/host
# Get with decryptionaws ssm get-parameter --name /myapp/database/password --with-decryptionQ148: How do you use SSM Session Manager?
Section titled “Q148: How do you use SSM Session Manager?”Answer:
# Start sessionaws ssm start-session --target i-1234567890abcdef0
# Terminate sessionaws ssm terminate-session --session-id session-idAWS CLI Tips
Section titled “AWS CLI Tips”Q149: How do you use JMESPath with AWS CLI?
Section titled “Q149: How do you use JMESPath with AWS CLI?”Answer:
# Query instance IDsaws ec2 describe-instances \ --query 'Reservations[*].Instances[*].InstanceId'
# Query with filteraws ec2 describe-instances \ --filters "Name=instance-state-name,Values=running" \ --query 'Instances[*].{ID:InstanceId,Type:InstanceType,Name:Tags[?Key==`Name`].Value|[0]}'
# Query with table outputaws ec2 describe-instances \ --query 'sort_by(Instances,&InstanceType)[*].{ID:InstanceId,Type:InstanceType,AZ:Placement.AvailabilityZone}'Q150: How do you use AWS CLI with JSON input?
Section titled “Q150: How do you use AWS CLI with JSON input?”Answer:
# From fileaws ec2 run-instances --cli-input-json file://instance.json
# instance.json{ "ImageId": "ami-0c55b159cbfafe1f0", "InstanceType": "t2.micro", "KeyName": "my-key", "SecurityGroupIds": ["sg-12345"], "SubnetId": "subnet-12345"}AWS SDK Examples
Section titled “AWS SDK Examples”Q151: How do you use boto3 to create EC2?
Section titled “Q151: How do you use boto3 to create EC2?”Answer:
import boto3
ec2 = boto3.resource('ec2')
# Create instanceinstance = ec2.create_instances( ImageId='ami-0c55b159cbfafe1f0', InstanceType='t2.micro', KeyName='my-key', SecurityGroupIds=['sg-12345'], SubnetId='subnet-12345', MaxCount=1, MinCount=1, TagSpecifications=[{ 'ResourceType': 'instance', 'Tags': [{'Key': 'Name', 'Value': 'MyInstance'}] }])[0]
print(f"Instance ID: {instance.id}")instance.wait_until_running()print("Instance is running")Q152: How do you use boto3 with S3?
Section titled “Q152: How do you use boto3 with S3?”Answer:
import boto3
s3 = boto3.client('s3')
# Upload files3.upload_file('local.txt', 'my-bucket', 'remote.txt')
# Download files3.download_file('my-bucket', 'remote.txt', 'local.txt')
# List bucketsresponse = s3.list_buckets()for bucket in response['Buckets']: print(bucket['Name'])
# Generate presigned URLurl = s3.generate_presigned_url( 'get_object', Params={'Bucket': 'my-bucket', 'Key': 'file.txt'}, ExpiresIn=3600)Q153: How do you use boto3 with DynamoDB?
Section titled “Q153: How do you use boto3 with DynamoDB?”Answer:
import boto3from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')table = dynamodb.Table('Users')
# Put itemtable.put_item(Item={'UserID': '1', 'Name': 'John', 'Age': 30})
# Get itemresponse = table.get_item(Key={'UserID': '1'})item = response.get('Item')
# Queryresponse = table.query( KeyConditionExpression=Key('UserID').eq('1'))
# Scan with filterresponse = table.scan( FilterExpression=Attr('Age').gt(25))Q154: How do you use boto3 with Lambda?
Section titled “Q154: How do you use boto3 with Lambda?”Answer:
import boto3import json
lambda_client = boto3.client('lambda')
# Invoke functionresponse = lambda_client.invoke( FunctionName='my-function', InvocationType='RequestResponse', Payload=json.dumps({'key': 'value'}))
result = json.loads(response['Payload'].read())print(result)Troubleshooting
Section titled “Troubleshooting”Q155: How do you troubleshoot EC2 connection issues?
Section titled “Q155: How do you troubleshoot EC2 connection issues?”Answer:
- Check security group allows SSH (port 22)
- Check route table has route to internet gateway
- Check internet gateway is attached
- Check instance has public IP
- Check NACL allows outbound traffic
- Verify key permissions:
chmod 400 key.pem - Check instance status checks
# Check instance statusaws ec2 describe-instance-status --instance-id i-12345
# Check security groupsaws ec2 describe-security-groups --group-ids sg-12345
# Check route tableaws ec2 describe-route-tables --route-table-id rtb-12345Q156: How do you troubleshoot RDS connection?
Section titled “Q156: How do you troubleshoot RDS connection?”Answer:
- Check security group allows database port (3306, 5432, etc.)
- Check subnet group has correct subnets
- Verify credentials
- Check if public access is enabled (if needed)
- Check VPC has correct route
# Get endpointaws rds describe-db-instances \ --db-instance-identifier mydb \ --query 'DBInstances[0].Endpoint'
# Check security groupaws rds describe-db-instances --db-instance-identifier mydb \ --query 'DBInstances[0].VpcSecurityGroups'Q157: How do you troubleshoot Lambda?
Section titled “Q157: How do you troubleshoot Lambda?”Answer:
- Check CloudWatch Logs
- Check function configuration (timeout, memory, VPC)
- Check IAM role permissions
- Check VPC configuration (if configured)
- Check for cold start issues
# Get logsaws logs filter-log-events \ --log-group-name /aws/lambda/my-function \ --filter-pattern "ERROR"
# Check function configaws lambda get-function-configuration --function-name my-functionQ158: How do you troubleshoot S3 access denied?
Section titled “Q158: How do you troubleshoot S3 access denied?”Answer:
- Check bucket policy
- Check IAM policy on principal
- Check ACL on bucket/object
- Check VPC endpoint policy
- Check public access settings
# Get bucket policyaws s3api get-bucket-policy --bucket my-bucket
# Check public accessaws s3api get-public-access-block --bucket my-bucketQ159: How do you troubleshoot API Gateway 5xx errors?
Section titled “Q159: How do you troubleshoot API Gateway 5xx errors?”Answer:
- Check CloudWatch logs for API Gateway
- Check Lambda logs for errors
- Verify integration timeout
- Check Lambda returns correct format
- Verify CORS settings
# Get execution logsaws logs filter-log-events \ --log-group-name /aws/apigateway/my-api \ --filter-pattern "5xx"Q160: How do you troubleshoot CloudFront?
Section titled “Q160: How do you troubleshoot CloudFront?”Answer:
- Check origin is accessible
- Verify cache behavior settings
- Check SSL certificate
- Check route 53 DNS
- Check error responses
# Get distribution configaws cloudfront get-distribution-config --id distribution-id
# Check field-level encryptionaws cloudfront list-field-level-encryption-profilesCost Optimization
Section titled “Cost Optimization”Q161: How do you find unused EBS volumes?
Section titled “Q161: How do you find unused EBS volumes?”Answer:
# Find unattached volumesaws ec2 describe-volumes \ --filters "Name=status,Values=available" \ --query 'Volumes[*].{ID:VolumeId,Size:Size,Type:VolumeType}'Q162: How do you find unused EIP?
Section titled “Q162: How do you find unused EIP?”Answer:
# Find unassociated EIPsaws ec2 describe-addresses \ --filters "Name=association-state,Values=null" \ --query 'Addresses[*].{AllocationId:AllocationId,PublicIP:PublicIp}'Q163: How do you enable AWS Cost Anomaly Detection?
Section titled “Q163: How do you enable AWS Cost Anomaly Detection?”Answer:
# Create anomaly monitoraws ce create-anomaly-monitor \ --anomaly-monitor '{ "MonitorName": "RootAccountUsage", "MonitorType": "DIMENSIONAL", "MonitorDimension": "LINKED_ACCOUNT" }'
# Create subscriptionaws ce create-anomaly-subscription \ --anomaly-subscription '{ "SubscriptionName": "EmailAlert", "Threshold": 100, "MonitorArnList": ["arn:aws:ce:us-east-1:123456789012:anomaly/monitor/12345"], "Subscribers": [{"Address": "admin@example.com", "Type": "EMAIL"}] }'Security Hardening
Section titled “Security Hardening”Q164: How do you enable VPC Flow Logs?
Section titled “Q164: How do you enable VPC Flow Logs?”Answer:
# Create log groupaws logs create-log-group --log-group-name /aws/vpc/flowlogs
# Create flow logsaws ec2 create-flow-logs \ --resource-type VPC \ --resource-ids vpc-1234567890abcdef0 \ --traffic-type ALL \ --log-destination-type cloud-watch-logs \ --log-group-name /aws/vpc/flowlogs \ --deliver-logs-permission-role-arn arn:aws:iam::123456789012:role/FlowLogsRoleQ165: How do you enable CloudTrail in all regions?
Section titled “Q165: How do you enable CloudTrail in all regions?”Answer:
# Create multi-region trailaws cloudtrail create-trail \ --name my-trail \ --s3-bucket-name my-cloudtrail-bucket \ --is-multi-region-trail \ --include-global-service-events \ --enable-log-file-validationQ166: How do you enable GuardDuty?
Section titled “Q166: How do you enable GuardDuty?”Answer:
# Enable GuardDutyaws guardduty create-detector \ --enable
# Create findings filteraws guardduty create-filter \ --detector-id detector-id \ --name high-severity \ --finding-criteria '{"Criterion": {"severity": {"Eq": [8]}}}'Disaster Recovery
Section titled “Disaster Recovery”Q167: How do you create cross-region RDS replica?
Section titled “Q167: How do you create cross-region RDS replica?”Answer:
# Create read replica in different regionaws rds create-db-instance-read-replica \ --db-instance-identifier mydb-replica-us-west-2 \ --source-db-instance-identifier arn:aws:rds:us-east-1:123456789012:db:mydb \ --region us-west-2 \ --db-instance-class db.t3.microQ168: How do you copy RDS snapshot to another region?
Section titled “Q168: How do you copy RDS snapshot to another region?”Answer:
# Copy snapshotaws rds copy-db-snapshot \ --source-db-snapshot-identifier arn:aws:rds:us-east-1:123456789012:snapshot:mydb-snap \ --target-db-snapshot-identifier mydb-snap-us-west-2 \ --region us-west-2 \ --copy-tagsQ169: How do you set up S3 cross-region replication?
Section titled “Q169: How do you set up S3 cross-region replication?”Answer:
# Enable versioning on both bucketsaws s3api put-bucket-versioning \ --bucket source-bucket \ --versioning-configuration Status=Enabled
aws s3api put-bucket-versioning \ --bucket dest-bucket \ --versioning-configuration Status=Enabled
# Enable replicationaws s3api put-bucket-replication \ --bucket source-bucket \ --replication-configuration '{ "Role": "arn:aws:iam::123456789012:role/replication-role", "Rules": [{ "ID": "replicate-all", "Status": "Enabled", "Destination": {"Bucket": "arn:aws:s3:::dest-bucket"} }] }'Backup and Restore
Section titled “Backup and Restore”Q170: How do you create EBS snapshot and restore?
Section titled “Q170: How do you create EBS snapshot and restore?”Answer:
# Create snapshotaws ec2 create-snapshot \ --volume-id vol-1234567890abcdef0 \ --description "Backup of data volume"
# Restore from snapshotaws ec2 create-volume \ --snapshot-id snap-1234567890abcdef0 \ --availability-zone us-east-1a
# Attachaws ec2 attach-volume \ --volume-id vol-new \ --instance-id i-1234567890abcdef0 \ --device /dev/sdfQ171: How do you automate backups with Data Lifecycle Manager?
Section titled “Q171: How do you automate backups with Data Lifecycle Manager?”Answer:
# Create lifecycle policyaws dlm create-lifecycle-policy \ --description "Daily EBS snapshots" \ --state ENABLED \ --policy-details '{ "ResourceTypes": ["VOLUME"], "TargetTags": [{"Key": "Backup", "Value": "true"}], "Schedules": [{ "Name": "DailyBackup", "CreateRule": {"Interval": 24, "IntervalUnit": "HOURS"}, "RetainRule": {"Count": 7} }] }'Performance
Section titled “Performance”Q172: How do you enable enhanced networking on EC2?
Section titled “Q172: How do you enable enhanced networking on EC2?”Answer:
# Enable enhanced networking (requires correct AMI and instance type)# For ENA:aws ec2 modify-instance-attribute \ --instance-id i-1234567890abcdef0 \ --ena-support
# For Intel 82599:aws ec2 modify-instance-attribute \ --instance-id i-1234567890abcdef0 \ --sriov-net-support simpleQ173: How do you optimize S3 performance?
Section titled “Q173: How do you optimize S3 performance?”Answer:
- Use S3 Transfer Acceleration
- Use multipart upload for large files
- Use CloudFront for caching
- Use appropriate key prefixes for high throughput
- Use S3 Intelligent-Tiering
# Enable Transfer Accelerationaws s3api put-bucket-accelerate-configuration \ --bucket my-bucket \ --accelerate-configuration Status=EnabledQ174: How do you optimize RDS performance?
Section titled “Q174: How do you optimize RDS performance?”Answer:
- Use Provisioned IOPS for SSD
- Create read replicas for read-heavy workloads
- Use ElastiCache for caching
- Optimize queries with proper indexing
- Enable Performance Insights
- Right-size instance
High Availability
Section titled “High Availability”Q175: How do you set up ALB with multiple AZ?
Section titled “Q175: How do you set up ALB with multiple AZ?”Answer:
# Create target groupaws elbv2 create-target-group \ --name my-tg \ --protocol HTTP \ --port 80 \ --vpc-id vpc-1234567890abcdef0 \ --health-check-path /health
# Register instances in multiple AZsaws elbv2 register-targets \ --target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-tg/12345 \ --targets Id=i-1234567890abcdef0,AvailabilityZone=us-east-1a Id=i-0987654321fedcba0,AvailabilityZone=us-east-1b
# Create ALB with subnets in multiple AZsaws elbv2 create-load-balancer \ --name my-alb \ --subnets subnet-12345 subnet-67890 subnet-abcd \ --security-groups sg-12345Q176: How do you set up Route 53 failover?
Section titled “Q176: How do you set up Route 53 failover?”Answer:
# Create primary recordaws route53 change-resource-record-sets \ --hosted-zone-id Z1234567890ABCDEF \ --change-batch '{ "Changes": [{ "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com", "Type": "A", "Failover": "PRIMARY", "SetIdentifier": "primary", "AliasTarget": { "HostedZoneId": "Z1234567890ABCDEF", "DNSName": "myalb-1234567890.us-east-1.elb.amazonaws.com", "EvaluateTargetHealth": true }, "HealthCheckId": "health-check-id-1" } }] }'Additional Scenarios
Section titled “Additional Scenarios”Q177: How do you migrate EC2 to another account?
Section titled “Q177: How do you migrate EC2 to another account?”Answer:
- Create AMI from source instance
- Share AMI with target account
- Copy AMI in target account
- Launch instance from copied AMI
# In source account:aws ec2 create-image --instance-id i-123 --name "MyAMI"
# Share AMIaws ec2 modify-image-attribute \ --image-id ami-123 \ --attribute launchPermission \ --operation-type add \ --user-ids 123456789012
# In target account:aws ec2 copy-image \ --source-image-id ami-123 \ --source-region us-east-1 \ --name "MyAMI-Copied"Q178: How do you set up Private API Gateway?
Section titled “Q178: How do you set up Private API Gateway?”Answer:
# Create VPC endpoint for API Gatewayaws ec2 create-vpc-endpoint \ --vpc-id vpc-1234567890abcdef0 \ --service-name com.amazonaws.us-east-1.execute-api \ --vpc-endpoint-type Interface \ --subnet-ids subnet-12345 subnet-67890Q179: How do you enable S3 inventory?
Section titled “Q179: How do you enable S3 inventory?”Answer:
# Create bucket for inventoryaws s3 mb s3://inventory-bucket
# Configure inventoryaws s3api put-bucket-inventory-configuration \ --bucket my-bucket \ --inventory-configuration '{ "Id": "inventory-config", "Destination": { "S3BucketDestination": { "Format": "CSV", "Bucket": "arn:aws:s3:::inventory-bucket" } }, "IncludedObjectVersions": "All", "Schedule": {"Frequency": "Daily"} }'Q180: How do you use AWS Config for compliance?
Section titled “Q180: How do you use AWS Config for compliance?”Answer:
# Enable AWS Configaws configservice put-configuration-recorder \ --configuration-recorder Name=default \ --rolearn arn:aws:iam::123456789012:role/config-role
# Put delivery channelaws configservice put-delivery-channel \ --delivery-channel '{ "name": "default", "s3BucketName": "config-bucket", "snsTopicArn": "arn:aws:sns:us-east-1:123456789012:config-topic" }'
# Start recorderaws configservice start-configuration-recorder --configuration-recorder-name defaultQuestions 181-200: Advanced Scenarios
Section titled “Questions 181-200: Advanced Scenarios”Q181: How do you set up AWS Transfer Family for SFTP?
Section titled “Q181: How do you set up AWS Transfer Family for SFTP?”Answer:
# Create serveraws transfer create-server \ --identity-provider-type SERVICE_MANAGED \ --protocols SFTP
# Create useraws transfer create-user \ --server-id s-1234567890abcdef0 \ --user-name myuser \ --ssh-public-key-body "ssh-rsa AAAAB..." \ --role arn:aws:iam::123456789012:role/transfer-user-role \ --home-directory /my-bucket/myuserQ182: How do you use Systems Manager Parameter Store with SecureString?
Section titled “Q182: How do you use Systems Manager Parameter Store with SecureString?”Answer:
import boto3
ssm = boto3.client('ssm')
# Create secure stringssm.put_parameter( Name='/myapp/db/password', Value='encrypted_password', Type='SecureString', KeyId='alias/aws/ssm' # Uses AWS managed key)
# Get parameterresponse = ssm.get_parameter( Name='/myapp/db/password', WithDecryption=True)password = response['Parameter']['Value']Q183: How do you set up EventBridge schedule?
Section titled “Q183: How do you set up EventBridge schedule?”Answer:
# Create rule with scheduleaws events put-rule \ --name daily-backup \ --schedule-expression "cron(0 2 * * ? *)" \ --state ENABLED
# Add targetaws events put-targets \ --rule daily-backup \ --targets '[{"Id":"1","Arn":"arn:aws:lambda:us-east-1:123456789012:function:daily-backup"}]'Q184: How do you use CloudFormation StackSets?
Section titled “Q184: How do you use CloudFormation StackSets?”Answer:
# Create stack setaws cloudformation create-stack-set \ --stack-set-name my-stackset \ --template-body file://template.yaml
# Add stacks to accounts/regionsaws cloudformation create-stack-instances \ --stack-set-name my-stackset \ --accounts '["123456789012"]' \ --regions '["us-east-1","us-west-2"]' \ --operation-preferences FailureToleranceCount=0,MaxConcurrentCount=1Q185: How do you configure RDS proxy?
Section titled “Q185: How do you configure RDS proxy?”Answer:
# Create RDS proxyaws rds create-db-proxy \ --db-proxy-name my-proxy \ --engine-family MYSQL \ --auth '["SecretArn":"arn:aws:secretsmanager:us-east-1:123456789012:secret:db-credentials"]' \ --role-arn arn:aws:iam::123456789012:role/rds-proxy-role \ --vpc-subnet-ids subnet-12345 subnet-67890
# Register targetsaws rds register-db-proxyTargets \ --db-proxy-name my-proxy \ --target-group-name default \ --db-instance-identifiers mydbQ186: How do you enable S3 Object Lock?
Section titled “Q186: How do you enable S3 Object Lock?”Answer:
# Create bucket with object lockaws s3api create-bucket \ --bucket my-locked-bucket \ --object-lock-enabled-for-bucket
# Put object lock retentionaws s3api put-object-retention \ --bucket my-locked-bucket \ --key myfile.txt \ --retention '{"Mode":"GOVERNANCE","RetainUntilDate":"2025-01-01T00:00:00Z"}'Q187: How do you use S3 Access Points?
Section titled “Q187: How do you use S3 Access Points?”Answer:
# Create access pointaws s3control create-access-point \ --account-id 123456789012 \ --name my-access-point \ --bucket my-bucket
# Access using access points3://my-access-point--accountid.s3-accesspoint.us-east-1.amazonaws.com/myfile.txtQ188: How do you configure EFS access points?
Section titled “Q188: How do you configure EFS access points?”Answer:
# Create access pointaws efs create-access-point \ --file-system-id fs-1234567890abcdef0 \ --access-point-name my-ap \ --posix-user '{"Uid":1000,"Gid":1000}' \ --root-directory '{"Path":"/exports/data","CreationInfo":{"OwnerGid":1000,"OwnerUid":1000,"Permissions":"0755"}}'Q189: How do you set up PrivateLink for ALB?
Section titled “Q189: How do you set up PrivateLink for ALB?”Answer:
# Create VPC endpoint for ALBaws ec2 create-vpc-endpoint \ --vpc-id vpc-1234567890abcdef0 \ --service-name com.amazonaws.us-east-1.elasticloadbalancing \ --vpc-endpoint-type Interface \ --subnet-ids subnet-12345 subnet-67890 \ --security-group-ids sg-12345Q190: How do you use AWS Config Rules for security?
Section titled “Q190: How do you use AWS Config Rules for security?”Answer:
# Enable AWS Config ruleaws configservice put-config-rule \ --config-rule '{ "ConfigRuleName": "s3-bucket-public-read-prohibited", "Source": { "Owner": "AWS", "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED" }, "Scope": { "ComplianceResourceTypes": ["AWS::S3::Bucket"] } }'Q191: How do you set up Amazon Inspector?
Section titled “Q191: How do you set up Amazon Inspector?”Answer:
# Enable Inspectoraws inspector enable \ --assessment-targets '["arn:aws:inspector:us-east-1:123456789012:target/0-abc"]' \ --rules-package-arns '["arn:aws:inspector:us-east-1:123456789012:rulespackage/0-abc"]'
# Create assessment templateaws inspector create-assessment-template \ --assessment-target-arn arn:aws:inspector:us-east-1:123456789012:target/0-abc \ --duration 3600 \ --rules-package-arns '["arn:aws:inspector:us-east-1:123456789012:rulespackage/0-abc"]'Q192: How do you use AWS Secrets Manager with rotation?
Section titled “Q192: How do you use AWS Secrets Manager with rotation?”Answer:
# Create secret with rotationaws secretsmanager create-secret \ --name prod/db-credentials \ --secret-string '{"username":"admin","password":"currentpassword"}' \ --rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:rotation-function \ --rotation-rules AutomaticallyAfterDays=30Q193: How do you set up AWS WAF?
Section titled “Q193: How do you set up AWS WAF?”Answer:
# Create web ACLaws wafv2 create-web-acl \ --name my-web-acl \ --scope CLOUDFRONT \ --default-action '{"Allow":{}}'
# Add ruleaws wafv2 put-logging-configuration \ --log-destination-configurations '[{"ARN":"arn:aws:wafv2:us-east-1:123456789012:loggingconfiguration/abc","RedactedFields":[{"FieldToMatch":{"SingleQueryArgument":{"Name":"password"}}}]}]'Q194: How do you configure AWS Backup?
Section titled “Q194: How do you configure AWS Backup?”Answer:
# Create backup planaws backup create-backup-plan \ --backup-plan '{ "BackupPlan": { "BackupPlanName": "daily-backup", "Rules": [{ "RuleName": "daily-backup-rule", "TargetBackupVaultName": "default", "ScheduleExpression": "cron(0 5 ? * * *)", "Lifecycle": {"MoveToColdStorageAfterDays": 30} }] } }'Q195: How do you use AWS Marketplace?
Section titled “Q195: How do you use AWS Marketplace?”Answer:
# Subscribe to productaws marketplace subscribe \ --product-arn arn:aws:aws-marketplace:us-east-1:123456789012:product/abc
# List subscriptionsaws marketplace list-subscriptionsQ196: How do you enable AWS Detective?
Section titled “Q196: How do you enable AWS Detective?”Answer:
# Enable Detectiveaws detective create-graph \ --region us-east-1
# Add memberaws detective create-members \ --graph-arn arn:aws:detective:us-east-1:123456789012:graph/abc \ --accounts '[{"AccountId":"123456789012","EmailAddress":"admin@example.com"}]'Q197: How do you use AWS Systems Manager Quick Setup?
Section titled “Q197: How do you use AWS Systems Manager Quick Setup?”Answer:
# Create Quick Setupaws ssm create-association \ --name "AWS-QuickSetup-ConfigWin" \ --targets '[{"Key":"InstanceIds","Values":["i-123"]}]'Q198: How do you enable VPC Reachability Analyzer?
Section titled “Q198: How do you enable VPC Reachability Analyzer?”Answer:
# Create pathaws ec2-reachability-analyzer create-path \ --source '{"InstanceId":"i-1234567890abcdef0"}' \ --destination '{"InstanceId":"i-0987654321fedcba0"}'
# Get path resultaws ec2-reachability-analyzer get-path \ --path-id path-idQ199: How do you use AWS Migration Hub?
Section titled “Q199: How do you use AWS Migration Hub?”Answer:
# Register applicationaws migrationhub create-application \ --name my-application
# Discovered resourceaws migrationhub list-discovered-resources \ --account-id 123456789012 \ --region us-east-1Q200: How do you use AWS Application Discovery Service?
Section titled “Q200: How do you use AWS Application Discovery Service?”Answer:
# Start agentless discoveryaws discovery start-agentless-connection \ --connector-configuration '{ "ConnectorName": "my-connector", "SubnetId": "subnet-12345", "SecurityGroupId": "sg-12345" }'
# Get agentsaws discovery list-agentsContinue with Questions 201-300 in next file…