Skip to content

AWS_Practical_Interview_101 200

AWS Practical Interview Questions (101-200)

Section titled “AWS Practical Interview Questions (101-200)”

Q101: How do you create CloudFront distribution?

Section titled “Q101: How do you create CloudFront distribution?”

Answer:

Terminal window
# Create distribution
aws cloudfront create-distribution \
--origin-domain-name mybucket.s3.amazonaws.com \
--default-root-object index.html \
--enabled \
--price-class PriceClass_All

Q102: How do you set up CloudFront with S3?

Section titled “Q102: How do you set up CloudFront with S3?”

Answer:

Terminal window
# Create OAI
aws cloudfront create-cloud-front-origin-access-identity \
--cloud-front-origin-access-identity-config CallerReference="my-oai",Comment="OAI for S3"
# Update S3 bucket policy
aws 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 boto3
import datetime
cloudfront = boto3.client('cloudfront')
# Create signed URL
url = 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:

Terminal window
# Invalidate all files
aws cloudfront create-invalidation \
--distribution-id E1234567890ABC \
--paths "/*"
# Invalidate specific files
aws cloudfront create-invalidation \
--distribution-id E1234567890ABC \
--paths "/index.html" "/images/*.jpg"

Answer:

Terminal window
# Create EFS
aws efs create-file-system \
--throughput-mode bursting \
--encrypted \
--performance-mode generalPurpose
# Create mount target
aws efs create-mount-target \
--file-system-id fs-1234567890abcdef0 \
--subnet-id subnet-12345 \
--security-groups sg-12345

Answer:

Terminal window
# Install EFS utils
sudo yum install -y amazon-efs-utils
# Mount EFS
sudo mount -t efs fs-1234567890abcdef0:/ /mnt/efs
# Mount with TLS
sudo mount -t efs -o tls fs-1234567890abcdef0:/ /mnt/efs

Answer:

Terminal window
# Create FSx for Windows
aws 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"
}'

Q108: How do you connect to RDS using SSL?

Section titled “Q108: How do you connect to RDS using SSL?”

Answer:

Terminal window
# Download SSL certificate
wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
# Connect with SSL
mysql -h mydb.xxxx.rds.amazonaws.com \
-u admin -p \
--ssl-ca=rds-combined-ca-bundle.pem \
--ssl-mode=REQUIRED

Q109: How do you change RDS instance class?

Section titled “Q109: How do you change RDS instance class?”

Answer:

Terminal window
# Modify RDS instance
aws rds modify-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.medium \
--apply-immediately
# Or for planned maintenance window
aws rds modify-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.medium \
--apply-during-maintenance-window

Q110: How do you enable RDS performance insights?

Section titled “Q110: How do you enable RDS performance insights?”

Answer:

Terminal window
# Enable Performance Insights
aws rds create-performance-insights-encryption-default \
--aws-region us-east-1
# Or on instance
aws rds modify-db-instance \
--db-instance-identifier mydb \
--enable-performance-insights \
--performance-insights-kms-key-id key-id

Answer:

Terminal window
# Restore MySQL from S3
aws 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 100

Q112: How do you configure RDS parameter group?

Section titled “Q112: How do you configure RDS parameter group?”

Answer:

Terminal window
# Create parameter group
aws rds create-db-parameter-group \
--db-parameter-group-name my-param-group \
--db-parameter-group-family mysql8.0 \
--description "Custom parameter group"
# Modify parameter
aws 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:

Terminal window
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 TTL
aws dynamodb update-time-to-live \
--table-name Orders \
--time-to-live-specification Enabled=true,AttributeName=TTL

Q114: How do you create VPC endpoint for S3?

Section titled “Q114: How do you create VPC endpoint for S3?”

Answer:

Terminal window
# Create endpoint
aws 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 S3

Q115: How do you create VPC endpoint for DynamoDB?

Section titled “Q115: How do you create VPC endpoint for DynamoDB?”

Answer:

Terminal window
# Create endpoint
aws ec2 create-vpc-endpoint \
--vpc-id vpc-1234567890abcdef0 \
--service-name com.amazonaws.us-east-1.dynamodb \
--route-table-ids rtb-12345
Section titled “Q116: How do you set up PrivateLink (interface endpoint)?”

Answer:

Terminal window
# Create interface endpoint
aws 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-67890

Q117: How do you configure VPC DNS options?

Section titled “Q117: How do you configure VPC DNS options?”

Answer:

Terminal window
# Enable DNS hostname
aws ec2 modify-vpc-attribute \
--vpc-id vpc-1234567890abcdef0 \
--enable-dns-hostnames "{\"Value\":true}"
# Enable DNS support
aws 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:

Terminal window
# Create VPC
VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query 'Vpc.VpcId' --output text)
# Create public subnet
PUBLIC_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 subnet
PRIVATE_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 IGW
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
# Create public route table
ROUTE_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_ID
aws ec2 associate-route-table --route-table-id $ROUTE_TABLE --subnet-id $PUBLIC_SUBNET

Q119: How do you set up Lambda destination?

Section titled “Q119: How do you set up Lambda destination?”

Answer:

Terminal window
# Configure destination for success
aws 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"}
}'

Answer:

Terminal window
# Enable SnapStart for Java functions
aws lambda update-function-configuration \
--function-name my-java-function \
--snap-start '{"ApplyOn":"PublishedVersions"}'
# Publish version
aws lambda publish-version --function-name my-java-function

Q121: How do you configure reserved concurrency?

Section titled “Q121: How do you configure reserved concurrency?”

Answer:

Terminal window
# Set reserved concurrency
aws lambda put-function-concurrency \
--function-name my-function \
--reserved-concurrent-executions 10
# Remove reserved concurrency
aws lambda delete-function-concurrency --function-name my-function

Q122: How do you set up provisioned concurrency?

Section titled “Q122: How do you set up provisioned concurrency?”

Answer:

Terminal window
# Configure provisioned concurrency
aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--qualifier 5 \
--provisioned-concurrent-executions 5

Answer:

Terminal window
# Create layer
aws lambda publish-layer-version \
--layer-name my-layer \
--description "Pandas for data processing" \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.9
# Add to function
aws lambda update-function-configuration \
--function-name my-function \
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1

Q124: How do you create API Gateway REST API?

Section titled “Q124: How do you create API Gateway REST API?”

Answer:

Terminal window
# Create API
API_ID=$(aws apigateway create-rest-api \
--name my-api \
--query 'id' \
--output text)
# Get root resource
ROOT_ID=$(aws apigateway get-resources \
--rest-api-id $API_ID \
--query 'items[0].id' \
--output text)
# Create resource
RESOURCE_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:

Terminal window
# Create GET method
aws apigateway put-method \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--authorization-type NONE
# Create POST method with Lambda integration
aws 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/invocations

Q126: How do you set up API Gateway usage plan?

Section titled “Q126: How do you set up API Gateway usage plan?”

Answer:

Terminal window
# Create usage plan
aws apigateway create-usage-plan \
--name my-usage-plan \
--api-stages apiId=abc123,stage=prod \
--quota '{"Limit":10000,"Period":"MONTH"}' \
--throttle '{"BurstLimit":100,"RateLimit":50}'

Answer:

Terminal window
# Create API key
aws apigateway create-api-key \
--name my-api-key \
--enabled
# Add to usage plan
aws apigateway create-usage-plan-key \
--usage-plan-id abc123 \
--key-id xyz789 \
--key-type API_KEY

Q128: How do you configure API Gateway caching?

Section titled “Q128: How do you configure API Gateway caching?”

Answer:

Terminal window
# Enable caching on stage
aws apigateway update-stage \
--rest-api-id $API_ID \
--stage-name prod \
--patch-operations '[{"op":"replace","path":"/*/settings/cacheEnabled","value":"true"}]'
# Set cache ttl
aws apigateway update-stage \
--rest-api-id $API_ID \
--stage-name prod \
--patch-operations '[{"op":"replace","path":"/*/settings/cacheTtlInSeconds","value":"300"}]'

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 data
cloudwatch.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:

Terminal window
# Create topic
TOPIC_ARN=$(aws sns create-topic --name cpu-alarm --query 'TopicArn' --output text)
# Subscribe email
aws sns subscribe \
--topic-arn $TOPIC_ARN \
--protocol email \
--notification-endpoint admin@example.com
# Create alarm
aws 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_ARN

Q131: How do you create CloudWatch composite alarm?

Section titled “Q131: How do you create CloudWatch composite alarm?”

Answer:

Terminal window
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-topic

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 UseEncryptedStorage

Q133: 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: mysql

Q134: 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.micro

Q135: 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: 1

Q136: 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'}

Answer:

Terminal window
# Update service
aws 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 deployment
aws ecs update-service \
--cluster my-cluster \
--service my-service \
--force-new-deployment

Q138: 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:

Terminal window
# Create namespace
aws servicediscovery create-private-dns-namespace \
--name local \
--vpc vpc-1234567890abcdef0
# Create service with discovery
aws 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"}'

Answer:

Terminal window
# Create FIFO topic
aws sns create-topic \
--name my-fifo-topic.fifo \
--attributes '{
"FifoTopic": "true",
"ContentBasedDeduplication": "true"
}'
# Subscribe SQS to SNS
aws 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.fifo

Q141: How do you configure SQS dead letter queue?

Section titled “Q141: How do you configure SQS dead letter queue?”

Answer:

Terminal window
# Create DLQ
aws sqs create-queue \
--queue-name my-dlq.fifo \
--attributes '{"FifoQueue":"true","ContentBasedDeduplication":"true"}'
# Create main queue with DLQ
aws 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:

Terminal window
# Send message with attributes
aws 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"}
}'

Answer:

Terminal window
# Create stream
aws kinesis create-stream \
--stream-name my-stream \
--shard-count 2
# Describe stream
aws kinesis describe-stream-summary \
--stream-name my-stream
# List streams
aws kinesis list-streams

Answer:

Terminal window
# Put record
aws 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=="}]'

Answer:

Terminal window
# Get iterator
SHARD_ITERATOR=$(aws kinesis get-shard-iterator \
--stream-name my-stream \
--shard-id shardId-000000000000 \
--shard-iterator-type LATEST \
--query 'ShardIterator' \
--output text)
# Get records
aws kinesis get-records \
--shard-iterator $SHARD_ITERATOR

Q146: How do you run command on EC2 using SSM?

Section titled “Q146: How do you run command on EC2 using SSM?”

Answer:

Terminal window
# Send command
aws 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 status
aws ssm list-command-invocations \
--command-id command-id

Answer:

Terminal window
# Create parameter
aws ssm put-parameter \
--name /myapp/database/host \
--value mydb.xxx.rds.amazonaws.com \
--type String
# Create secure string
aws ssm put-parameter \
--name /myapp/database/password \
--value mypassword123 \
--type SecureString
# Get parameter
aws ssm get-parameter --name /myapp/database/host
# Get with decryption
aws ssm get-parameter --name /myapp/database/password --with-decryption

Answer:

Terminal window
# Start session
aws ssm start-session --target i-1234567890abcdef0
# Terminate session
aws ssm terminate-session --session-id session-id

Q149: How do you use JMESPath with AWS CLI?

Section titled “Q149: How do you use JMESPath with AWS CLI?”

Answer:

Terminal window
# Query instance IDs
aws ec2 describe-instances \
--query 'Reservations[*].Instances[*].InstanceId'
# Query with filter
aws 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 output
aws 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:

Terminal window
# From file
aws 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"
}

Answer:

import boto3
ec2 = boto3.resource('ec2')
# Create instance
instance = 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")

Answer:

import boto3
s3 = boto3.client('s3')
# Upload file
s3.upload_file('local.txt', 'my-bucket', 'remote.txt')
# Download file
s3.download_file('my-bucket', 'remote.txt', 'local.txt')
# List buckets
response = s3.list_buckets()
for bucket in response['Buckets']:
print(bucket['Name'])
# Generate presigned URL
url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': 'my-bucket', 'Key': 'file.txt'},
ExpiresIn=3600
)

Answer:

import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
# Put item
table.put_item(Item={'UserID': '1', 'Name': 'John', 'Age': 30})
# Get item
response = table.get_item(Key={'UserID': '1'})
item = response.get('Item')
# Query
response = table.query(
KeyConditionExpression=Key('UserID').eq('1')
)
# Scan with filter
response = table.scan(
FilterExpression=Attr('Age').gt(25)
)

Answer:

import boto3
import json
lambda_client = boto3.client('lambda')
# Invoke function
response = lambda_client.invoke(
FunctionName='my-function',
InvocationType='RequestResponse',
Payload=json.dumps({'key': 'value'})
)
result = json.loads(response['Payload'].read())
print(result)

Q155: How do you troubleshoot EC2 connection issues?

Section titled “Q155: How do you troubleshoot EC2 connection issues?”

Answer:

  1. Check security group allows SSH (port 22)
  2. Check route table has route to internet gateway
  3. Check internet gateway is attached
  4. Check instance has public IP
  5. Check NACL allows outbound traffic
  6. Verify key permissions: chmod 400 key.pem
  7. Check instance status checks
Terminal window
# Check instance status
aws ec2 describe-instance-status --instance-id i-12345
# Check security groups
aws ec2 describe-security-groups --group-ids sg-12345
# Check route table
aws ec2 describe-route-tables --route-table-id rtb-12345

Q156: How do you troubleshoot RDS connection?

Section titled “Q156: How do you troubleshoot RDS connection?”

Answer:

  1. Check security group allows database port (3306, 5432, etc.)
  2. Check subnet group has correct subnets
  3. Verify credentials
  4. Check if public access is enabled (if needed)
  5. Check VPC has correct route
Terminal window
# Get endpoint
aws rds describe-db-instances \
--db-instance-identifier mydb \
--query 'DBInstances[0].Endpoint'
# Check security group
aws rds describe-db-instances --db-instance-identifier mydb \
--query 'DBInstances[0].VpcSecurityGroups'

Answer:

  1. Check CloudWatch Logs
  2. Check function configuration (timeout, memory, VPC)
  3. Check IAM role permissions
  4. Check VPC configuration (if configured)
  5. Check for cold start issues
Terminal window
# Get logs
aws logs filter-log-events \
--log-group-name /aws/lambda/my-function \
--filter-pattern "ERROR"
# Check function config
aws lambda get-function-configuration --function-name my-function

Q158: How do you troubleshoot S3 access denied?

Section titled “Q158: How do you troubleshoot S3 access denied?”

Answer:

  1. Check bucket policy
  2. Check IAM policy on principal
  3. Check ACL on bucket/object
  4. Check VPC endpoint policy
  5. Check public access settings
Terminal window
# Get bucket policy
aws s3api get-bucket-policy --bucket my-bucket
# Check public access
aws s3api get-public-access-block --bucket my-bucket

Q159: How do you troubleshoot API Gateway 5xx errors?

Section titled “Q159: How do you troubleshoot API Gateway 5xx errors?”

Answer:

  1. Check CloudWatch logs for API Gateway
  2. Check Lambda logs for errors
  3. Verify integration timeout
  4. Check Lambda returns correct format
  5. Verify CORS settings
Terminal window
# Get execution logs
aws logs filter-log-events \
--log-group-name /aws/apigateway/my-api \
--filter-pattern "5xx"

Answer:

  1. Check origin is accessible
  2. Verify cache behavior settings
  3. Check SSL certificate
  4. Check route 53 DNS
  5. Check error responses
Terminal window
# Get distribution config
aws cloudfront get-distribution-config --id distribution-id
# Check field-level encryption
aws cloudfront list-field-level-encryption-profiles

Answer:

Terminal window
# Find unattached volumes
aws ec2 describe-volumes \
--filters "Name=status,Values=available" \
--query 'Volumes[*].{ID:VolumeId,Size:Size,Type:VolumeType}'

Answer:

Terminal window
# Find unassociated EIPs
aws 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:

Terminal window
# Create anomaly monitor
aws ce create-anomaly-monitor \
--anomaly-monitor '{
"MonitorName": "RootAccountUsage",
"MonitorType": "DIMENSIONAL",
"MonitorDimension": "LINKED_ACCOUNT"
}'
# Create subscription
aws 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"}]
}'

Answer:

Terminal window
# Create log group
aws logs create-log-group --log-group-name /aws/vpc/flowlogs
# Create flow logs
aws 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/FlowLogsRole

Q165: How do you enable CloudTrail in all regions?

Section titled “Q165: How do you enable CloudTrail in all regions?”

Answer:

Terminal window
# Create multi-region trail
aws cloudtrail create-trail \
--name my-trail \
--s3-bucket-name my-cloudtrail-bucket \
--is-multi-region-trail \
--include-global-service-events \
--enable-log-file-validation

Answer:

Terminal window
# Enable GuardDuty
aws guardduty create-detector \
--enable
# Create findings filter
aws guardduty create-filter \
--detector-id detector-id \
--name high-severity \
--finding-criteria '{"Criterion": {"severity": {"Eq": [8]}}}'

Q167: How do you create cross-region RDS replica?

Section titled “Q167: How do you create cross-region RDS replica?”

Answer:

Terminal window
# Create read replica in different region
aws 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.micro

Q168: How do you copy RDS snapshot to another region?

Section titled “Q168: How do you copy RDS snapshot to another region?”

Answer:

Terminal window
# Copy snapshot
aws 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-tags

Q169: How do you set up S3 cross-region replication?

Section titled “Q169: How do you set up S3 cross-region replication?”

Answer:

Terminal window
# Enable versioning on both buckets
aws s3api put-bucket-versioning \
--bucket source-bucket \
--versioning-configuration Status=Enabled
aws s3api put-bucket-versioning \
--bucket dest-bucket \
--versioning-configuration Status=Enabled
# Enable replication
aws 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"}
}]
}'

Q170: How do you create EBS snapshot and restore?

Section titled “Q170: How do you create EBS snapshot and restore?”

Answer:

Terminal window
# Create snapshot
aws ec2 create-snapshot \
--volume-id vol-1234567890abcdef0 \
--description "Backup of data volume"
# Restore from snapshot
aws ec2 create-volume \
--snapshot-id snap-1234567890abcdef0 \
--availability-zone us-east-1a
# Attach
aws ec2 attach-volume \
--volume-id vol-new \
--instance-id i-1234567890abcdef0 \
--device /dev/sdf

Q171: How do you automate backups with Data Lifecycle Manager?

Section titled “Q171: How do you automate backups with Data Lifecycle Manager?”

Answer:

Terminal window
# Create lifecycle policy
aws 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}
}]
}'

Q172: How do you enable enhanced networking on EC2?

Section titled “Q172: How do you enable enhanced networking on EC2?”

Answer:

Terminal window
# 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 simple

Answer:

  1. Use S3 Transfer Acceleration
  2. Use multipart upload for large files
  3. Use CloudFront for caching
  4. Use appropriate key prefixes for high throughput
  5. Use S3 Intelligent-Tiering
Terminal window
# Enable Transfer Acceleration
aws s3api put-bucket-accelerate-configuration \
--bucket my-bucket \
--accelerate-configuration Status=Enabled

Q174: How do you optimize RDS performance?

Section titled “Q174: How do you optimize RDS performance?”

Answer:

  1. Use Provisioned IOPS for SSD
  2. Create read replicas for read-heavy workloads
  3. Use ElastiCache for caching
  4. Optimize queries with proper indexing
  5. Enable Performance Insights
  6. Right-size instance

Q175: How do you set up ALB with multiple AZ?

Section titled “Q175: How do you set up ALB with multiple AZ?”

Answer:

Terminal window
# Create target group
aws elbv2 create-target-group \
--name my-tg \
--protocol HTTP \
--port 80 \
--vpc-id vpc-1234567890abcdef0 \
--health-check-path /health
# Register instances in multiple AZs
aws 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 AZs
aws elbv2 create-load-balancer \
--name my-alb \
--subnets subnet-12345 subnet-67890 subnet-abcd \
--security-groups sg-12345

Q176: How do you set up Route 53 failover?

Section titled “Q176: How do you set up Route 53 failover?”

Answer:

Terminal window
# Create primary record
aws 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"
}
}]
}'

Q177: How do you migrate EC2 to another account?

Section titled “Q177: How do you migrate EC2 to another account?”

Answer:

  1. Create AMI from source instance
  2. Share AMI with target account
  3. Copy AMI in target account
  4. Launch instance from copied AMI
Terminal window
# In source account:
aws ec2 create-image --instance-id i-123 --name "MyAMI"
# Share AMI
aws 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:

Terminal window
# Create VPC endpoint for API Gateway
aws 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-67890

Answer:

Terminal window
# Create bucket for inventory
aws s3 mb s3://inventory-bucket
# Configure inventory
aws 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:

Terminal window
# Enable AWS Config
aws configservice put-configuration-recorder \
--configuration-recorder Name=default \
--rolearn arn:aws:iam::123456789012:role/config-role
# Put delivery channel
aws configservice put-delivery-channel \
--delivery-channel '{
"name": "default",
"s3BucketName": "config-bucket",
"snsTopicArn": "arn:aws:sns:us-east-1:123456789012:config-topic"
}'
# Start recorder
aws configservice start-configuration-recorder --configuration-recorder-name default

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:

Terminal window
# Create server
aws transfer create-server \
--identity-provider-type SERVICE_MANAGED \
--protocols SFTP
# Create user
aws 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/myuser

Q182: 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 string
ssm.put_parameter(
Name='/myapp/db/password',
Value='encrypted_password',
Type='SecureString',
KeyId='alias/aws/ssm' # Uses AWS managed key
)
# Get parameter
response = 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:

Terminal window
# Create rule with schedule
aws events put-rule \
--name daily-backup \
--schedule-expression "cron(0 2 * * ? *)" \
--state ENABLED
# Add target
aws 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:

Terminal window
# Create stack set
aws cloudformation create-stack-set \
--stack-set-name my-stackset \
--template-body file://template.yaml
# Add stacks to accounts/regions
aws cloudformation create-stack-instances \
--stack-set-name my-stackset \
--accounts '["123456789012"]' \
--regions '["us-east-1","us-west-2"]' \
--operation-preferences FailureToleranceCount=0,MaxConcurrentCount=1

Answer:

Terminal window
# Create RDS proxy
aws 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 targets
aws rds register-db-proxyTargets \
--db-proxy-name my-proxy \
--target-group-name default \
--db-instance-identifiers mydb

Answer:

Terminal window
# Create bucket with object lock
aws s3api create-bucket \
--bucket my-locked-bucket \
--object-lock-enabled-for-bucket
# Put object lock retention
aws s3api put-object-retention \
--bucket my-locked-bucket \
--key myfile.txt \
--retention '{"Mode":"GOVERNANCE","RetainUntilDate":"2025-01-01T00:00:00Z"}'

Answer:

Terminal window
# Create access point
aws s3control create-access-point \
--account-id 123456789012 \
--name my-access-point \
--bucket my-bucket
# Access using access point
s3://my-access-point--accountid.s3-accesspoint.us-east-1.amazonaws.com/myfile.txt

Q188: How do you configure EFS access points?

Section titled “Q188: How do you configure EFS access points?”

Answer:

Terminal window
# Create access point
aws 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"}}'
Section titled “Q189: How do you set up PrivateLink for ALB?”

Answer:

Terminal window
# Create VPC endpoint for ALB
aws 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-12345

Q190: How do you use AWS Config Rules for security?

Section titled “Q190: How do you use AWS Config Rules for security?”

Answer:

Terminal window
# Enable AWS Config rule
aws 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"]
}
}'

Answer:

Terminal window
# Enable Inspector
aws 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 template
aws 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:

Terminal window
# Create secret with rotation
aws 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=30

Answer:

Terminal window
# Create web ACL
aws wafv2 create-web-acl \
--name my-web-acl \
--scope CLOUDFRONT \
--default-action '{"Allow":{}}'
# Add rule
aws wafv2 put-logging-configuration \
--log-destination-configurations '[{"ARN":"arn:aws:wafv2:us-east-1:123456789012:loggingconfiguration/abc","RedactedFields":[{"FieldToMatch":{"SingleQueryArgument":{"Name":"password"}}}]}]'

Answer:

Terminal window
# Create backup plan
aws backup create-backup-plan \
--backup-plan '{
"BackupPlan": {
"BackupPlanName": "daily-backup",
"Rules": [{
"RuleName": "daily-backup-rule",
"TargetBackupVaultName": "default",
"ScheduleExpression": "cron(0 5 ? * * *)",
"Lifecycle": {"MoveToColdStorageAfterDays": 30}
}]
}
}'

Answer:

Terminal window
# Subscribe to product
aws marketplace subscribe \
--product-arn arn:aws:aws-marketplace:us-east-1:123456789012:product/abc
# List subscriptions
aws marketplace list-subscriptions

Answer:

Terminal window
# Enable Detective
aws detective create-graph \
--region us-east-1
# Add member
aws 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:

Terminal window
# Create Quick Setup
aws 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:

Terminal window
# Create path
aws ec2-reachability-analyzer create-path \
--source '{"InstanceId":"i-1234567890abcdef0"}' \
--destination '{"InstanceId":"i-0987654321fedcba0"}'
# Get path result
aws ec2-reachability-analyzer get-path \
--path-id path-id

Answer:

Terminal window
# Register application
aws migrationhub create-application \
--name my-application
# Discovered resource
aws migrationhub list-discovered-resources \
--account-id 123456789012 \
--region us-east-1

Q200: How do you use AWS Application Discovery Service?

Section titled “Q200: How do you use AWS Application Discovery Service?”

Answer:

Terminal window
# Start agentless discovery
aws discovery start-agentless-connection \
--connector-configuration '{
"ConnectorName": "my-connector",
"SubnetId": "subnet-12345",
"SecurityGroupId": "sg-12345"
}'
# Get agents
aws discovery list-agents

Continue with Questions 201-300 in next file…