Skip to content

AWS_Practical_Interview_1 100

Answer:

Terminal window
# AWS CLI
aws ec2 run-instances \
--image-id ami-0c55b159cbfafe1f0 \
--instance-type t2.micro \
--key-name my-key-pair \
--security-group-ids sg-1234567890abcdef0 \
--subnet-id subnet-1234567890abcdef0 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyInstance}]'

Key Points:

  • Choose appropriate AMI (Amazon Machine Image)
  • Select instance type based on workload
  • Key pair for SSH access
  • Security group for network access

Answer:

Terminal window
# Linux/Mac
ssh -i "my-key.pem" ec2-user@<public-ip>
# Windows (PuTTY)
# Convert .pem to .ppk using PuTTYgen, then connect
# With verbose for debugging
ssh -vvv -i "my-key.pem" ec2-user@<public-ip>

Key Points:

  • Use correct username (ec2-user, ubuntu, centos, etc.)
  • Ensure security group allows SSH (port 22)
  • Key file must have correct permissions: chmod 400 my-key.pem

Q3: Can you attach multiple security groups to an EC2 instance?

Section titled “Q3: Can you attach multiple security groups to an EC2 instance?”

Answer: Yes, you can attach up to 5 security groups to an EC2 instance. Security groups are additive - all rules from all attached security groups are applied.

Terminal window
# AWS CLI to add security groups
aws ec2 modify-instance-attribute \
--instance-id i-1234567890abcdef0 \
--groups sg-12345 sg-67890

Answer:

Terminal window
# Describe instance status
aws ec2 describe-instance-status --instance-id i-1234567890abcdef0
# List all instances
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running"
# Check system status and instance status
aws ec2 describe-instance-status \
--instance-id i-1234567890abcdef0 \
--include-all-instances

Q5: How do you stop and start an EC2 instance?

Section titled “Q5: How do you stop and start an EC2 instance?”

Answer:

Terminal window
# Stop instance
aws ec2 stop-instances --instance-id i-1234567890abcdef0
# Start instance
aws ec2 start-instances --instance-id i-1234567890abcdef0
# Reboot instance
aws ec2 reboot-instances --instance-id i-1234567890abcdef0

Q6: How do you create an AMI from an EC2 instance?

Section titled “Q6: How do you create an AMI from an EC2 instance?”

Answer:

Terminal window
# Create AMI
aws ec2 create-image \
--instance-id i-1234567890abcdef0 \
--name "My-AMI-$(date +%Y%m%d)" \
--description "Custom AMI with Apache" \
--no-reboot
# List AMIs
aws ec2 describe-images --owners self

Q7: How do you launch an EC2 instance with user data (bootstrap script)?

Section titled “Q7: How do you launch an EC2 instance with user data (bootstrap script)?”

Answer:

Terminal window
# Launch with user data
aws ec2 run-instances \
--image-id ami-0c55b159cbfafe1f0 \
--instance-type t2.micro \
--key-name my-key \
--security-group-ids sg-12345 \
--subnet-id subnet-12345 \
--user-data file://install-httpd.sh
# Example install-httpd.sh:
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from EC2</h1>" > /var/www/html/index.html

Q8: What is EC2 instance metadata and how do you access it?

Section titled “Q8: What is EC2 instance metadata and how do you access it?”

Answer: Instance metadata is data about the instance that you can use to configure or manage the running instance.

Terminal window
# Get instance metadata
curl http://169.254.169.254/latest/meta-data/
# Get specific metadata
curl http://169.254.169.254/latest/meta-data/instance-id
curl http://169.254.169.254/latest/meta-data/public-ipv4
curl http://169.254.169.254/latest/meta-data/ami-id
# Get user data
curl http://169.254.169.254/latest/user-data/

Answer:

Terminal window
# Step 1: Modify volume
aws ec2 modify-volume \
--volume-id vol-1234567890abcdef0 \
--size 50
# Step 2: Check status
aws ec2 describe-volumes-modifications \
--volume-ids vol-1234567890abcdef0
# Step 3: Extend file system (Linux)
sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1

Q10: Can you encrypt an existing EBS volume?

Section titled “Q10: Can you encrypt an existing EBS volume?”

Answer: You CANNOT directly encrypt an unencrypted EBS volume. Workarounds:

Method 1: Create encrypted snapshot

Terminal window
# Create snapshot
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "Backup"
# Copy with encryption
aws ec2 copy-snapshot \
--source-snapshot-id snap-1234567890abcdef0 \
--encrypted \
--description "Encrypted snapshot"
# Create volume from encrypted snapshot
aws ec2 create-volume \
--snapshot-id snap-newencrypted \
--availability-zone us-east-1a \
--encrypted

Method 2: Replace instance with encrypted volume

  1. Stop instance
  2. Create snapshot
  3. Create encrypted snapshot
  4. Create new volume from encrypted snapshot
  5. Attach to instance

Q11: What is the difference between Security Group and NACL?

Section titled “Q11: What is the difference between Security Group and NACL?”

Answer:

AspectSecurity GroupNACL
LevelInstance/ENISubnet
StatefulYes (return traffic auto-allowed)No (stateless)
RulesAllow onlyAllow and Deny
EvaluationAll rules evaluatedProcessed in order
DefaultDeny all inbound, Allow all outboundAllow all by default

Q12: How do you allow HTTP traffic to EC2?

Section titled “Q12: How do you allow HTTP traffic to EC2?”

Answer:

Terminal window
# Create security group
aws ec2 create-security-group \
--group-name web-sg \
--description "Security group for web servers" \
--vpc-id vpc-1234567890abcdef0
# Add inbound rule for HTTP
aws ec2 authorize-security-group-ingress \
--group-id sg-1234567890abcdef0 \
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0
# Add HTTPS
aws ec2 authorize-security-group-ingress \
--group-id sg-1234567890abcdef0 \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0

Q13: How do you allow specific IP access to EC2?

Section titled “Q13: How do you allow specific IP access to EC2?”

Answer:

Terminal window
# Allow specific IP
aws ec2 authorize-security-group-ingress \
--group-id sg-1234567890abcdef0 \
--protocol tcp \
--port 22 \
--cidr 203.0.113.0/24

Q14: How do you allow another security group in security group?

Section titled “Q14: How do you allow another security group in security group?”

Answer:

Terminal window
# Allow traffic from another security group
aws ec2 authorize-security-group-ingress \
--group-id sg-1234567890abcdef0 \
--protocol all \
--source-group sg-othergroup

Q15: What is VPC and how do you create one?

Section titled “Q15: What is VPC and how do you create one?”

Answer:

Terminal window
# Create VPC
aws ec2 create-vpc --cidr-block 10.0.0.0/16
# Enable DNS hostnames
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}"

Answer:

Terminal window
# Create subnet
aws ec2 create-subnet \
--vpc-id vpc-1234567890abcdef0 \
--cidr-block 10.0.1.0/24 \
--availability-zone us-east-1a
# Enable auto-assign public IP
aws ec2 modify-subnet-attribute \
--subnet-id subnet-1234567890abcdef0 \
--map-public-ip-on-launch
# Create and attach Internet Gateway
aws ec2 create-internet-gateway
aws ec2 attach-internet-gateway \
--internet-gateway-id igw-1234567890abcdef0 \
--vpc-id vpc-1234567890abcdef0
# Create route table and add route
aws ec2 create-route-table --vpc-id vpc-1234567890abcdef0
aws ec2 create-route \
--route-table-id rtb-1234567890abcdef0 \
--destination-cidr-block 0.0.0.0/0 \
--gateway-id igw-1234567890abcdef0

Answer:

Terminal window
# Create Elastic IP
aws ec2 allocate-address --domain vpc
# Create NAT Gateway
aws ec2 create-nat-gateway \
--subnet-id subnet-public-id \
--allocation-id eipalloc-id
# Create route table for private subnet
aws ec2 create-route-table --vpc-id vpc-1234567890abcdef0
aws ec2 create-route \
--route-table-id rtb-private \
--destination-cidr-block 0.0.0.0/0 \
--nat-gateway-id nat-1234567890abcdef0
# Associate route table with private subnet
aws ec2 associate-route-table \
--route-table-id rtb-private \
--subnet-id subnet-private-id

Answer:

Terminal window
# Create peering connection
aws ec2 create-vpc-peering-connection \
--vpc-id vpc-1234567890abcdef0 \
--peer-vpc-id vpc-0987654321fedcba0
# Accept peering connection (in peer account)
aws ec2 accept-vpc-peering-connection \
--vpc-peering-connection-id pcx-1234567890abcdef0
# Update route tables (in both VPCs)
aws ec2 create-route \
--route-table-id rtb-1234567890abcdef0 \
--destination-cidr-block 10.1.0.0/16 \
--vpc-peering-connection-id pcx-1234567890abcdef0

Q19: How do you connect to private EC2 without bastion?

Section titled “Q19: How do you connect to private EC2 without bastion?”

Answer:

Terminal window
# Using SSM Session Manager
# Step 1: Install SSM Agent on instance (pre-installed on Amazon Linux 2)
# Step 2: Attach IAM role with SSM permissions
aws ec2 associate-iam-instance-profile \
--instance-id i-1234567890abcdef0 \
--iam-instance-profile Name=SSM-Role
# Step 3: Start session
aws ssm start-session --target i-1234567890abcdef0
# Or use AWS Console → Systems Manager → Session Manager

Q20: What is the difference between NAT Gateway and NAT Instance?

Section titled “Q20: What is the difference between NAT Gateway and NAT Instance?”

Answer:

AspectNAT GatewayNAT Instance
Managed by AWSYesNo (you manage)
AvailabilityHigh availability (multiple AZs)Single instance
PerformanceUp to 45 GbpsDepends on instance type
CostPer hour + data processingPer hour + data processing
MaintenanceAWS handlesYou handle updates

Answer:

Terminal window
# Simple upload
aws s3 cp myfile.txt s3://my-bucket/
# Upload with specific permissions
aws s3 cp myfile.txt s3://my-bucket/ --acl private
# Upload recursively
aws s3 cp ./folder s3://my-bucket/ --recursive
# Upload with encryption
aws s3 cp myfile.txt s3://my-bucket/ --sse AES256

Answer: Not recommended, but if needed:

Terminal window
# Disable block public access
aws s3api put-public-access-block \
--bucket my-bucket \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"
# Add bucket policy for public read
aws s3api put-bucket-policy \
--bucket my-bucket \
--policy '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*"
}]
}'

Answer:

Terminal window
# Enable versioning
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled
# Enable MFA delete (requires MFA)
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled,MFADelete=Enabled \
--mfa "ARN-OF-MFA-DELETE count-of-mfa-code"

Q24: How do you set up S3 lifecycle policy?

Section titled “Q24: How do you set up S3 lifecycle policy?”

Answer:

Terminal window
# Create lifecycle configuration
aws s3api put-bucket-lifecycle-configuration \
--bucket my-bucket \
--lifecycle-configuration '{
"Rules": [
{
"ID": "Move to IA after 30 days",
"Status": "Enabled",
"Transitions": [
{
"Days": 30,
"StorageClass": "STANDARD_IA"
},
{
"Days": 90,
"StorageClass": "GLACIER"
},
{
"Days": 365,
"StorageClass": "DEEP_ARCHIVE"
}
]
},
{
"ID": "Delete after 7 years",
"Status": "Enabled",
"Expiration": {
"Days": 2555
}
}
]
}'

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
# Create IAM role for replication
aws iam create-role --role-name S3-Replication-Role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "s3.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
# Add replication policy to role (attach policy)
aws iam put-role-policy --role-name S3-Replication-Role \
--policy-name Replication-Policy \
--policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObjectVersion", "s3:GetObjectVersionAcl"],
"Resource": "arn:aws:s3:::source-bucket/*"
},
{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:PutObjectAcl"],
"Resource": "arn:aws:s3:::dest-bucket/*"
}]
}'
# Enable replication on source bucket
aws s3api put-bucket-replication \
--bucket source-bucket \
--replication-configuration '{
"Role": "arn:aws:iam::123456789012:role/S3-Replication-Role",
"Rules": [{
"ID": "ReplicateAll",
"Status": "Enabled",
"Destination": {
"Bucket": "arn:aws:s3:::dest-bucket"
}
}]
}'

Answer:

Terminal window
# Using S3 CLI
aws s3 ls s3://my-bucket --recursive --summarize
# Output shows:
# Total Objects: 1000
# Total Size: 123.45 GB
# Using CloudWatch
aws cloudwatch get-metric-statistics \
--namespace AWS/S3 \
--metric-name BucketSizeBytes \
--start-time 2024-01-01T00:00:00Z \
--end-time 2024-01-02T00:00:00Z \
--period 86400 \
--statistics Average \
--dimensions Name=BucketName,Value=my-bucket

Answer:

Terminal window
# Enable default encryption with KMS
aws s3api put-bucket-encryption \
--bucket my-bucket \
--server-side-encryption-configuration '{
"Rules": [{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "AES256"
}
}]
}'
# Or with KMS key
aws s3api put-bucket-encryption \
--bucket my-bucket \
--server-side-encryption-configuration '{
"Rules": [{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "aws:kms",
"KMSKeyId": "arn:aws:kms:us-east-1:123456789012:key/key-id"
}
}]
}'

Q28: How do you set up static website hosting on S3?

Section titled “Q28: How do you set up static website hosting on S3?”

Answer:

Terminal window
# Enable static website hosting
aws s3 website s3://my-bucket \
--index-document index.html \
--error-document error.html
# Set bucket policy for public access (after unblocking public access)
aws s3api put-bucket-policy \
--bucket my-bucket \
--policy '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*"
}]
}'
# Website URL format:
# http://my-bucket.s3-website-us-east-1.amazonaws.com

Q29: How do you generate S3 presigned URL?

Section titled “Q29: How do you generate S3 presigned URL?”

Answer:

Terminal window
# Generate presigned URL for download (valid for 1 hour)
aws s3 presign s3://my-bucket/myfile.txt --expires-in 3600
# Using Python boto3
import boto3
s3 = boto3.client('s3')
url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': 'my-bucket', 'Key': 'myfile.txt'},
ExpiresIn=3600
)
# For upload
url = s3.generate_presigned_url(
'put_object',
Params={'Bucket': 'my-bucket', 'Key': 'myfile.txt'},
ExpiresIn=3600
)

Answer:

Terminal window
# Create logging bucket
aws s3 mb s3://access-logs-bucket
# Grant log delivery permission
aws s3api put-bucket-acl \
--bucket my-bucket \
--grant-write URI=http://acs.amazonaws.com/groups/s3/LogDelivery \
--grant-read-acp URI=http://acs.amazonaws.com/groups/s3/LogDelivery
# Enable logging
aws s3api put-bucket-logging \
--bucket my-bucket \
--bucket-logging-status '{
"LoggingEnabled": {
"TargetBucket": "access-logs-bucket",
"TargetPrefix": "logs/"
}
}'

Answer:

Terminal window
# Create IAM user
aws iam create-user --user-name john
# Create access key
aws iam create-access-key --user-name john
# Attach policy
aws iam attach-user-policy \
--user-name john \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

Answer:

Terminal window
# Create role with trust policy
aws iam create-role \
--role-name EC2-S3-Role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
# Attach policy
aws iam attach-role-policy \
--role-name EC2-S3-Role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
# Create instance profile
aws iam create-instance-profile --instance-profile-name EC2-S3-Role
# Add role to instance profile
aws iam add-role-to-instance-profile \
--instance-profile-name EC2-S3-Role \
--role-name EC2-S3-Role
# Attach to EC2
aws ec2 associate-iam-instance-profile \
--instance-id i-1234567890abcdef0 \
--iam-instance-profile Name=EC2-S3-Role

Q33: How do you enable MFA on root account?

Section titled “Q33: How do you enable MFA on root account?”

Answer:

Terminal window
# List virtual MFA devices
aws iam list-mfa-devices --user-name root
# Enable MFA (requires ARN of MFA device)
aws iam enable-mfa-device \
--user-name root \
--serial-number arn:aws:iam::123456789012:mfa/root \
--authentication-code1 123456 \
--authentication-code2 789012

Answer:

Terminal window
# Create policy
aws iam create-policy \
--policy-name S3-Webapp-Policy \
--policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-webapp-bucket/*"
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": "arn:aws:s3:::my-webapp-bucket"
}
]
}'

Q35: What is the difference between IAM Policy and Resource Policy?

Section titled “Q35: What is the difference between IAM Policy and Resource Policy?”

Answer:

AspectIAM PolicyResource Policy
AttachmentTo users, groups, rolesTo resources (S3, Lambda)
Who definesIAM adminResource owner
PrincipalMust specifyCan use wildcard
EvaluationBoth can allowOnly one can deny

Answer:

Terminal window
# Test policy
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::123456789012:user/john \
--action-names s3:GetObject \
--resource-arns arn:aws:s3:::my-bucket/myfile.txt

Q37: How do you set up cross-account access?

Section titled “Q37: How do you set up cross-account access?”

Answer:

Terminal window
# Account A (owner): Create role with trust policy
aws iam create-role \
--name CrossAccount-Role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"AWS": "arn:aws:iam::123456789012:user/admin"},
"Action": "sts:AssumeRole"
}]
}'
# Account B (user): Assume role
aws sts assume-role \
--role-arn arn:aws:iam::111111111111:role/CrossAccount-Role \
--role-session-name cross-account-session

Answer:

Terminal window
# Create new access key
aws iam create-access-key --user-name john
# Update configuration with new key
# List access keys
aws iam list-access-keys --user-name john
# Deactivate old key
aws iam update-access-key \
--access-key-id AKIAIOSFODNN7EXAMPLE \
--status Inactive \
--user-name john
# Delete old key after confirming
aws iam delete-access-key \
--access-key-id AKIAIOSFODNN7EXAMPLE \
--user-name john

Q39: How do you set up AWS Secrets Manager?

Section titled “Q39: How do you set up AWS Secrets Manager?”

Answer:

Terminal window
# Create secret
aws secretsmanager create-secret \
--name prod/db_credentials \
--secret-string '{"username":"admin","password":"secret123"}'
# Get secret value
aws secretsmanager get-secret-value \
--secret-id prod/db_credentials
# Rotate secret (requires Lambda)
aws secretsmanager rotate-secret \
--secret-id prod/db_credentials \
--rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:rotation-function

Answer:

Terminal window
# Create KMS key
aws kms create-key \
--description "My encryption key" \
--key-usage ENCRYPT_DECRYPT
# Create alias
aws kms create-alias \
--alias-name alias/my-key \
--target-key-id key-id
# Encrypt data
aws kms encrypt \
--key-id alias/my-key \
--plaintext "Hello World" \
--output text --query CiphertextBlob | base64 -d > encrypted.txt
# Decrypt data
aws kms decrypt \
--ciphertext-blob fileb://encrypted.txt \
--output text --query Plaintext | base64 -d

Answer:

Terminal window
# Create RDS instance (MySQL)
aws rds create-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.micro \
--engine mysql \
--allocated-storage 20 \
--master-username admin \
--master-user-password mypassword123 \
--vpc-security-group-ids sg-12345 \
--db-subnet-group-name my-subnet-group

Answer:

Terminal window
# Get endpoint
aws rds describe-db-instances \
--db-instance-identifier mydb \
--query 'DBInstances[0].Endpoint.Address'
# Connect using MySQL client
mysql -h mydb.xxxx.us-east-1.rds.amazonaws.com \
-u admin -p mydatabase

Answer:

Terminal window
# Modify DB instance for Multi-AZ
aws rds modify-db-instance \
--db-instance-identifier mydb \
--multi-az \
--apply-immediately
# Check status
aws rds describe-db-instances \
--db-instance-identifier mydb \
--query 'DBInstances[0].MultiAZ'

Answer:

Terminal window
# Create read replica
aws rds create-db-instance-read-replica \
--db-instance-identifier mydb-replica \
--source-db-instance-identifier mydb \
--db-instance-class db.t3.micro
# Promote to standalone (if needed)
aws rds promote-read-replica \
--db-instance-identifier mydb-replica

Answer:

Terminal window
# Create manual snapshot
aws rds create-db-snapshot \
--db-instance-identifier mydb \
--db-snapshot-identifier mydb-backup
# Restore from snapshot
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier mydb-restored \
--db-snapshot-identifier mydb-backup
# Point-in-time restore
aws rds restore-db-instance-to-point-in-time \
--source-db-instance-identifier mydb \
--target-db-instance-identifier mydb-pitr \
--restore-time 2024-01-15T12:00:00Z

Answer:

Terminal window
# Create DynamoDB table
aws dynamodb create-table \
--table-name Users \
--attribute-definitions \
AttributeName=UserID,AttributeType=N \
AttributeName=Email,AttributeType=S \
--key-schema \
AttributeName=UserID,KeyType=HASH \
--global-secondary-indexes '[{
"IndexName": "EmailIndex",
"KeySchema": [{"AttributeName":"Email","KeyType":"HASH"}],
"Projection":{"ProjectionType":"ALL"},
"ProvisionedThroughput":{"ReadCapacityUnits":5,"WriteCapacityUnits":5}
}]' \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

Answer:

Terminal window
# Get item by key
aws dynamodb get-item \
--table-name Users \
--key '{"UserID": {"N": "1"}}'
# Query with key condition
aws dynamodb query \
--table-name Users \
--key-condition-expression "UserID = :uid" \
--expression-attribute-values '{":uid": {"N": "1"}}'
# Scan (not recommended for large tables)
aws dynamodb scan \
--table-name Users \
--filter-expression "Age > :age" \
--expression-attribute-values '{":age": {"N": "25"}}'

Q48: How do you enable DynamoDB auto scaling?

Section titled “Q48: How do you enable DynamoDB auto scaling?”

Answer:

Terminal window
# Create scaling target
aws application-autoscaling put-scaling-target \
--resource-id table/Users \
--scalable-dimension dynamodb:table:WriteCapacityUnits \
--min-capacity 1 \
--max-capacity 10
# Create scaling policy
aws application-autoscaling put-scaling-policy \
--policy-name users-write-scaling \
--resource-id table/Users \
--scalable-dimension dynamodb:table:WriteCapacityUnits \
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
},
"TargetValue": 70.0
}'

Answer:

Terminal window
# Create function
aws lambda create-function \
--function-name my-function \
--runtime python3.9 \
--role arn:aws:iam::123456789012:role/lambda-role \
--handler index.lambda_handler \
--zip-file fileb://function.zip \
--timeout 30 \
--memory-size 128

Answer:

Terminal window
# Invoke directly
aws lambda invoke \
--function-name my-function \
--payload '{"key": "value"}' \
response.json
# Invoke with CLI (using --cli-binary-format)
aws lambda invoke \
--function-name my-function \
--payload '{"name": "World"}' \
--log-type Tail \
response.json
# Check logs
cat response.json

Q51: How do you set up Lambda trigger from S3?

Section titled “Q51: How do you set up Lambda trigger from S3?”

Answer:

Terminal window
# Add S3 event notification
aws s3api put-bucket-notification-configuration \
--bucket my-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [{
"Id": "my-trigger",
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
"Events": ["s3:ObjectCreated:*"]
}]
}'

Q52: How do you configure Lambda VPC access?

Section titled “Q52: How do you configure Lambda VPC access?”

Answer:

Terminal window
# Update function VPC config
aws lambda update-function-configuration \
--function-name my-function \
--vpc-config SubnetIds=subnet-12345,subnet-67890 \
--security-group-ids sg-12345

Answer:

Terminal window
# Create layer
aws lambda publish-layer-version \
--layer-name my-layer \
--description "My Python dependencies" \
--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

Q54: How do you set up API Gateway with Lambda?

Section titled “Q54: How do you set up API Gateway with Lambda?”

Answer:

Terminal window
# Create REST API
aws apigateway create-rest-api \
--name my-api
# Get resources and root ID
aws apigateway get-resources --rest-api-id api-id
# Create resource
aws apigateway create-resource \
--rest-api-id api-id \
--parent-id root-id \
--path-part hello
# Create method
aws apigateway put-method \
--rest-api-id api-id \
--resource-id resource-id \
--http-method GET \
--authorization-type NONE
# Create integration with Lambda
aws apigateway put-integration \
--rest-api-id api-id \
--resource-id resource-id \
--http-method GET \
--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
# Deploy API
aws apigateway create-deployment \
--rest-api-id api-id \
--stage-name prod

Q55: How do you configure Lambda environment variables?

Section titled “Q55: How do you configure Lambda environment variables?”

Answer:

Terminal window
# Set environment variables
aws lambda update-function-configuration \
--function-name my-function \
--environment Variables='{DB_HOST="mydb.xxx.rds.amazonaws.com","DB_NAME":"mydb"}'
# View environment variables
aws lambda get-function-configuration \
--function-name my-function \
--query Environment

Q56: How do you set up Lambda dead letter queue?

Section titled “Q56: How do you set up Lambda dead letter queue?”

Answer:

Terminal window
# Configure DLQ
aws lambda update-function-configuration \
--function-name my-function \
--dead-letter-config TargetArn=arn:aws:sqs:us-east-1:123456789012:my-dlq

Answer:

Terminal window
# Create alarm
aws cloudwatch put-metric-alarm \
--alarm-name cpu-high-alarm \
--alarm-description "Alarm when CPU exceeds 80%" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--statistic Average \
--period 300 \
--threshold 80 \
--comparison-operator GreaterThanThreshold \
--evaluation-periods 2 \
--alarm-actions arn:aws:sns:us-east-1:123456789012:my-topic

Q58: How do you create CloudWatch dashboard?

Section titled “Q58: How do you create CloudWatch dashboard?”

Answer:

Terminal window
# Create dashboard
aws cloudwatch put-dashboard \
--dashboard-name my-dashboard \
--dashboard-body '{
"widgets": [{
"type": "metric",
"properties": {
"title": "EC2 CPU",
"metrics": [
["AWS/EC2", "CPUUtilization", "InstanceId", "i-1234567890abcdef0"]
],
"period": 300,
"stat": "Average"
}
}]
}'

Q59: How do you create CloudWatch log subscription?

Section titled “Q59: How do you create CloudWatch log subscription?”

Answer:

Terminal window
# Create log group
aws logs create-log-group --log-group-name /aws/lambda/my-function
# Create filter
aws logs put-subscription-filter \
--log-group-name /aws/lambda/my-function \
--filter-name my-filter \
--filter-pattern "{ $.level = \"Error\" }" \
--destination-arn arn:aws:lambda:us-east-1:123456789012:function:my-processor

Answer:

Terminal window
# Create trail
aws cloudtrail create-trail \
--name my-trail \
--s3-bucket-name my-cloudtrail-bucket \
--is-multi-region-trail
# Start logging
aws cloudtrail start-logging --name my-trail
# Look up events
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventSource,AttributeValue=ec2.amazonaws.com

Q61: How do you create Auto Scaling group?

Section titled “Q61: How do you create Auto Scaling group?”

Answer:

Terminal window
# Create launch template
aws ec2 create-launch-template \
--launch-template-name my-template \
--launch-template-data '{
"ImageId": "ami-0c55b159cbfafe1f0",
"InstanceType": "t3.micro",
"KeyName": "my-key",
"SecurityGroupIds": ["sg-12345"]
}'
# Create ASG
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name my-asg \
--launch-template LaunchTemplateId=lt-12345 \
--min-size 2 \
--max-size 10 \
--desired-capacity 2 \
--vpc-zone-identifier "subnet-12345,subnet-67890"

Q62: How do you set up Auto Scaling policy?

Section titled “Q62: How do you set up Auto Scaling policy?”

Answer:

Terminal window
# Scale out policy
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name scale-out \
--policy-type SimpleScaling \
--adjustment-type PercentChangeInCapacity \
--scaling-adjustment 50 \
--cooldown 300
# Scale in policy
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name scale-in \
--policy-type SimpleScaling \
--adjustment-type ChangeInCapacity \
--scaling-adjustment -1
# Target tracking policy
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name target-tracking-cpu \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 70.0
}'

Answer:

Terminal window
# Create target group
aws elbv2 create-target-group \
--name my-targets \
--protocol HTTP \
--port 80 \
--vpc-id vpc-1234567890abcdef0
# Register targets
aws elbv2 register-targets \
--target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-targets/1234567890abcdef0 \
--targets Id=i-1234567890abcdef0 Id=i-0987654321fedcba0
# Create ALB
aws elbv2 create-load-balancer \
--name my-alb \
--subnets subnet-12345 subnet-67890 \
--security-groups sg-12345
# Create listener
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/my-alb/1234567890abcdef0 \
--protocol HTTP \
--port 80 \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-targets/1234567890abcdef0

Q64: How do you create CloudFormation stack?

Section titled “Q64: How do you create CloudFormation stack?”

Answer:

Terminal window
# Create stack
aws cloudformation create-stack \
--stack-name my-stack \
--template-body file://template.yaml \
--parameters ParameterKey=KeyName,ParameterValue=my-key \
--timeout-in-minutes 30
# Update stack
aws cloudformation update-stack \
--stack-name my-stack \
--template-body file://template.yaml \
--parameters ParameterKey=KeyName,ParameterValue=my-new-key
# Delete stack
aws cloudformation delete-stack --stack-name my-stack
# List stacks
aws cloudformation list-stacks
# Describe stack
aws cloudformation describe-stacks --stack-name my-stack

Q65: How do you use CloudFormation parameters?

Section titled “Q65: How do you use CloudFormation parameters?”

Answer:

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: EC2 Instance with Parameters
Parameters:
InstanceType:
Type: String
Default: t2.micro
AllowedValues:
- t2.micro
- t2.small
- t3.micro
Description: EC2 instance type
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: Name of an existing key pair
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0c55b159cbfafe1f0
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName

Q66: How do you use CloudFormation intrinsic functions?

Section titled “Q66: How do you use CloudFormation intrinsic functions?”

Answer:

# Using Ref
Instance: !Ref MyInstance
# Using GetAtt
AZ: !GetAtt MyInstance.AvailabilityZone
# Using Sub
Name: !Sub '${AWS::StackName}-instance'
# Using Join
Owner: !Join [",", ["admin@example.com", "dev@example.com"]]
# Using If
SecurityGroup: !If [UseDefaultSG, !Ref DefaultSG, !Ref CustomSG]
# Using Equals
Environment: !If [IsProduction, "prod", "dev"]

Q67: How do you use CloudFormation mappings?

Section titled “Q67: How do you use CloudFormation mappings?”

Answer:

Mappings:
RegionMap:
us-east-1:
AMI: ami-0c55b159cbfafe1f0
us-west-2:
AMI: ami-0a12345b67890cdef
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", AMI]

Q68: How do you use CloudFormation outputs?

Section titled “Q68: How do you use CloudFormation outputs?”

Answer:

Outputs:
InstanceID:
Description: Instance ID
Value: !Ref MyInstance
Export:
Name: !Sub '${AWS::StackName}-InstanceID'
PublicIP:
Description: Public IP Address
Value: !GetAtt MyInstance.PublicIp
InstanceURL:
Description: URL to access the application
Value: !Sub 'http://${MyInstance.PublicDnsName}'

Answer:

Terminal window
# Create cluster
aws ecs create-cluster \
--cluster-name my-cluster \
--capacity-providers FARGATE
# List clusters
aws ecs list-clusters
# Describe cluster
aws ecs describe-cluster --cluster my-cluster

Q70: How do you register ECS task definition?

Section titled “Q70: How do you register ECS task definition?”

Answer:

Terminal window
# Register task definition
aws ecs register-task-definition \
--family my-app \
--network-mode awsvpc \
--requires-compatibilities FARGATE \
--cpu "256" \
--memory "512" \
--container-definitions '[{
"name": "web",
"image": "nginx:latest",
"essential": true,
"portMappings": [{
"containerPort": 80,
"protocol": "tcp"
}]
}]'

Answer:

Terminal window
# Create service
aws ecs create-service \
--cluster my-cluster \
--service-name my-service \
--task-definition my-app:1 \
--desired-count 2 \
--launch-type FARGATE \
--network-configuration '{
"awsvpcConfiguration": {
"subnets": ["subnet-12345", "subnet-67890"],
"securityGroups": ["sg-12345"]
}
}' \
--load-balancers '[{
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-targets/1234567890",
"containerName": "web",
"containerPort": 80
}]'

Answer:

Terminal window
# Update service
aws ecs update-service \
--cluster my-cluster \
--service my-service \
--task-definition my-app:2 \
--desired-count 3
# View service events
aws ecs describe-services \
--cluster my-cluster \
--services my-service \
--query 'services[0].events'

Q73: How do you create Route 53 hosted zone?

Section titled “Q73: How do you create Route 53 hosted zone?”

Answer:

Terminal window
# Create hosted zone
aws route53 create-hosted-zone \
--name example.com \
--caller-reference "my-zone-$(date +%s)"
# List hosted zones
aws route53 list-hosted-zones

Q74: How do you create DNS record in Route 53?

Section titled “Q74: How do you create DNS record in Route 53?”

Answer:

Terminal window
# Create record
aws route53 change-resource-record-sets \
--hosted-zone-id Z1234567890ABCDEF \
--change-batch '{
"Changes": [{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "www.example.com",
"Type": "A",
"TTL": 300,
"ResourceRecords": [{"Value": "1.2.3.4"}]
}
}]
}'

Q75: How do you set up Route 53 health check?

Section titled “Q75: How do you set up Route 53 health check?”

Answer:

Terminal window
# Create health check
aws route53 create-health-check \
--caller-reference "healthcheck-$(date +%s)" \
--health-check-config '{
"Type": "HTTPS",
"FullyQualifiedDomainName": "example.com",
"Port": 443,
"ResourcePath": "/health",
"RequestInterval": 30,
"FailureThreshold": 3
}'
# Use in failover record
aws route53 change-resource-record-sets ...

Q76: How do you check SSL certificate expiration?

Section titled “Q76: How do you check SSL certificate expiration?”

Answer:

Terminal window
# Using OpenSSL
openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates
# Using AWS CLI
aws acm list-certificates --region us-east-1
# Using SSL Labs
# Visit https://ssllabs.com/ssltest/

Q77: How do you access EC2 instance through another instance?

Section titled “Q77: How do you access EC2 instance through another instance?”

Answer:

Terminal window
# SSH from bastion to private instance
ssh -i key.pem ec2-user@<private-ip-of-private-instance>
# SSH with proxy jump
ssh -J ec2-user@<bastion-ip> ec2-user@<private-ip>
# Using SSM (recommended)
aws ssm start-session --target i-private-instance-id

Q78: How do you upgrade EC2 with zero downtime?

Section titled “Q78: How do you upgrade EC2 with zero downtime?”

Answer:

  1. Using Auto Scaling Group:
Terminal window
# Update launch template with new instance type
aws ec2 create-launch-template-version \
--launch-template-id lt-12345 \
--launch-template-data '{"InstanceType":"t3.small"}'
# Update ASG to use new version
aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name my-asg \
--launch-template LaunchTemplateId=lt-12345,Version="2"
  1. Using Blue-Green:
  • Create new instance with larger type
  • Deploy application
  • Add to load balancer
  • Test
  • Remove old instance

Q79: How do you change IAM role with zero downtime?

Section titled “Q79: How do you change IAM role with zero downtime?”

Answer:

Terminal window
# Change IAM role
aws ec2 associate-iam-instance-profile \
--instance-id i-1234567890abcdef0 \
--iam-instance-profile Name=NewRole
# Note: Existing connections will continue to work
# New connections will use new role
# Applications should handle credential refresh

Answer:

  • SSL (Secure Sockets Layer) / TLS (Transport Layer Security)
  • Encrypts data in transit between browser and server
  • Authenticates website identity (prevents phishing)
  • Required for HTTPS
  • Improves SEO ranking
  • Builds user trust (padlock icon)
  • Required for PCI compliance

Q81: How do you check EC2 CPU utilization?

Section titled “Q81: How do you check EC2 CPU utilization?”
Terminal window
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--start-time 2024-01-01T00:00:00Z \
--end-time 2024-01-01T01:00:00Z \
--period 3600 \
--statistics Average \
--dimensions Name=InstanceId,Value=i-1234567890abcdef0

Q82: How do you find underutilized EC2 instances?

Section titled “Q82: How do you find underutilized EC2 instances?”
Terminal window
aws ce get-rightsizing-recommendations \
--service AmazonEC2 \
--recommendation-target-type COVERAGE

Q83: How do you enable detailed monitoring on EC2?

Section titled “Q83: How do you enable detailed monitoring on EC2?”
Terminal window
aws ec2 monitor-instances --instance-ids i-1234567890abcdef0
Terminal window
aws sns create-topic --name my-topic
# Subscribe
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:123456789012:my-topic \
--protocol email \
--notification-endpoint admin@example.com
Terminal window
aws sns publish \
--topic-arn arn:aws:sns:us-east-1:123456789012:my-topic \
--message "Alert: High CPU usage" \
--subject "CPU Alert"
Terminal window
aws sqs create-queue \
--queue-name my-queue \
--attributes '{"FifoQueue":"true","ContentBasedDeduplication":"true"}'
Terminal window
aws sqs send-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue \
--message-body '{"orderId": "123", "amount": 100}'
Terminal window
aws sqs receive-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue \
--max-number-of-messages 10
Terminal window
aws dynamodb update-table \
--table-name Users \
--global-secondary-index-updates '[{
"Create": {
"IndexName": "EmailIndex",
"KeySchema": [{"AttributeName":"Email","KeyType":"HASH"}],
"Projection":{"ProjectionType":"ALL"},
"ProvisionedThroughput":{"ReadCapacityUnits":5,"WriteCapacityUnits":5}
}
}]'
Terminal window
aws dynamodb update-time-to-live \
--table-name Orders \
--time-to-live-specification Enabled=true,AttributeName=ExpiresAt
Terminal window
aws lambda create-alias \
--function-name my-function \
--name PROD \
--function-version 3
Terminal window
aws lambda publish-version --function-name my-function
Terminal window
aws events put-rule \
--name ec2-state-change \
--event-pattern '{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"]}'
# Add target
aws events put-targets \
--rule ec2-state-change \
--targets '[{"Id":"my-target","Arn":"arn:aws:lambda:us-east-1:123456789012:function:my-function"}]'
Terminal window
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

Q95: How do you create CloudWatch logs group?

Section titled “Q95: How do you create CloudWatch logs group?”
Terminal window
aws logs create-log-group --log-group-name /my-app/logs

Q96: How do you create Secret with rotation?

Section titled “Q96: How do you create Secret with rotation?”
Terminal window
aws secretsmanager create-secret \
--name prod/db-creds \
--secret-string '{"username":"admin","password":"pass"}' \
--rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:rotation-fn \
--rotation-rules AutomaticallyAfterDays=30

Q97: How do you check EBS volume available IOPS?

Section titled “Q97: How do you check EBS volume available IOPS?”
Terminal window
aws ec2 describe-volume-attribute \
--volume-id vol-1234567890abcdef0 \
--attribute iops
Terminal window
aws ec2 create-volume \
--size 50 \
--availability-zone us-east-1a \
--volume-type gp3 \
--encrypted
Terminal window
aws ec2 attach-volume \
--volume-id vol-1234567890abcdef0 \
--instance-id i-1234567890abcdef0 \
--device /dev/sdf

Q100: How do you detach and delete EBS volume?

Section titled “Q100: How do you detach and delete EBS volume?”
Terminal window
# Detach
aws ec2 detach-volume --volume-id vol-1234567890abcdef0
# Delete
aws ec2 delete-volume --volume-id vol-1234567890abcdef0

Continue with Questions 101-200 in next file…