EC2, Lambda, Auto Scaling, and Fargate commands for production compute — launch, scale, connect, and monitor.
Launch an EC2 instance with key pair and Security Group.
aws ec2 run-instances \
--image-id ami-0f5ee92e2d63afc18 \
--instance-type t3.medium \
--key-name prod-key-ap-south-1 \
--security-group-ids sg-0a1b2c3d4e5f \
--subnet-id subnet-private-1a \
--iam-instance-profile Name=ec2-app-role \
--tag-specifications \
'ResourceType=instance,Tags=[{Key=Name,Value=prod-web-01},{Key=Environment,Value=prod}]' \
--region ap-south-1
Parameter Breakdown:
--image-id: AMI to boot from — use region-specific AMI ID--instance-type: CPU and RAM combination — t3.medium is 2 vCPU, 4 GB--iam-instance-profile: Attaches IAM Role — never use access keys on EC2--subnet-id: Target subnet — always use private subnet for app serversConnect without SSH keys or port 22 open.
## Start browser or CLI terminal session
aws ssm start-session \
--target i-0abc123def456789 \
--region ap-south-1
## Run a command on the instance
aws ssm send-command \
--instance-ids i-0abc123def456789 \
--document-name AWS-RunShellScript \
--parameters commands=["sudo systemctl restart nginx"] \
--region ap-south-1
Parameter Breakdown:
--target: EC2 instance ID — must have SSM Agent and AmazonSSMManagedInstanceCore role--document-name: SSM runbook to execute — AWS-RunShellScript runs arbitrary bashCreate a custom AMI for Auto Scaling Group Launch Templates.
## Create AMI from running instance
aws ec2 create-image \
--instance-id i-0abc123def456789 \
--name "prod-app-v1.4-$(date +%Y%m%d)" \
--description "App v1.4 with Node 20 and nginx 1.25" \
--no-reboot \
--region ap-south-1
## Copy AMI to another region for DR
aws ec2 copy-image \
--source-image-id ami-0123456789abcdef \
--source-region ap-south-1 \
--region ap-southeast-1 \
--name "prod-app-v1.4-singapore-copy"
## List your custom AMIs
aws ec2 describe-images \
--owners self \
--query 'Images[*].[ImageId,Name,CreationDate]' \
--output table \
--region ap-south-1
Parameter Breakdown:
--no-reboot: Creates image without stopping — safe for hot AMIs, may miss in-flight writes--owners self: Returns only AMIs you created — avoids noise from AWS public AMIsCreate an ASG with a Launch Template and target tracking policy.
## Create Launch Template
aws ec2 create-launch-template \
--launch-template-name prod-web-lt \
--launch-template-data '{
"ImageId": "ami-0123456789abcdef",
"InstanceType": "t3.medium",
"IamInstanceProfile": {"Name": "ec2-app-role"},
"SecurityGroupIds": ["sg-0a1b2c3d4e5f"],
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{"Key": "Environment","Value": "prod"}]
}]
}' \
--region ap-south-1
## Create ASG with the Launch Template
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name prod-web-asg \
--launch-template LaunchTemplateName=prod-web-lt,Version='$Latest' \
--min-size 2 \
--max-size 10 \
--desired-capacity 4 \
--vpc-zone-identifier "subnet-private-1a,subnet-private-1b" \
--health-check-type ELB \
--health-check-grace-period 60 \
--region ap-south-1
## Add target tracking scaling policy
aws autoscaling put-scaling-policy \
--auto-scaling-group-name prod-web-asg \
--policy-name cpu-target-50 \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 50.0,
"DisableScaleIn": false
}' \
--region ap-south-1
Parameter Breakdown:
--health-check-type ELB: Uses load balancer health check — detects app failures, not just OS statusTargetValue 50.0: Keeps average CPU at 50% — ASG adds instances above, removes below--min-size 2: Never fewer than 2 — required for multi-AZ high availabilityDeploy a Lambda function with VPC access and reserved concurrency.
## Create Lambda function from zip
aws lambda create-function \
--function-name prod-order-processor \
--runtime python3.12 \
--role arn:aws:iam::123456789012:role/lambda-exec-role \
--handler handler.lambda_handler \
--zip-file fileb://function.zip \
--memory-size 512 \
--timeout 30 \
--environment Variables='{
"DB_HOST":"db.internal.prod.in",
"QUEUE_URL":"https://sqs.ap-south-1.amazonaws.com/123456789012/orders"
}' \
--vpc-config \
SubnetIds=subnet-private-1a,subnet-private-1b,SecurityGroupIds=sg-lambda-prod \
--region ap-south-1
## Set reserved concurrency to protect critical function
aws lambda put-function-concurrency \
--function-name prod-order-processor \
--reserved-concurrent-executions 200 \
--region ap-south-1
## Enable SnapStart for Java functions (free cold start fix)
aws lambda put-function-configuration \
--function-name prod-java-processor \
--snap-start ApplyOn=PublishedVersions \
--region ap-south-1
Parameter Breakdown:
--memory-size 512: RAM in MB — also increases vCPU allocation proportionally--reserved-concurrent-executions 200: Guarantees 200 slots and prevents taking more--vpc-config: Deploys Lambda in private VPC — needed for private RDS/ElastiCache accessConnect SQS queue to Lambda for automatic queue processing.
## Create SQS event source mapping
aws lambda create-event-source-mapping \
--function-name prod-order-processor \
--event-source-arn arn:aws:sqs:ap-south-1:123456789012:prod-orders \
--batch-size 10 \
--maximum-batching-window-in-seconds 5 \
--function-response-types ReportBatchItemFailures \
--region ap-south-1
Parameter Breakdown:
--batch-size 10: Lambda receives up to 10 messages per invocation--function-response-types ReportBatchItemFailures: Failed individual messages go to DLQ--maximum-batching-window-in-seconds 5: Wait up to 5 seconds to fill a batchRun a one-off Fargate task and a persistent service.
## Run one-off Fargate task (batch job)
aws ecs run-task \
--cluster prod-cluster \
--task-definition prod-data-export:12 \
--launch-type FARGATE \
--network-configuration '{
"awsvpcConfiguration": {
"subnets": ["subnet-private-1a","subnet-private-1b"],
"securityGroups": ["sg-ecs-tasks"],
"assignPublicIp": "DISABLED"
}
}' \
--overrides '{
"containerOverrides": [{
"name": "exporter",
"environment": [{"name":"EXPORT_DATE","value":"2024-01-15"}]
}]
}' \
--region ap-south-1
## Update ECS service (rolling deploy)
aws ecs update-service \
--cluster prod-cluster \
--service prod-api-service \
--task-definition prod-api:25 \
--force-new-deployment \
--region ap-south-1
Parameter Breakdown:
--force-new-deployment: Triggers rolling replacement even with same task definitionassignPublicIp DISABLED: Never assign public IPs to Fargate tasks — use private subnets--overrides: Pass runtime environment variables without rebuilding the container image| Pricing Model | Discount vs On-Demand | Commitment | Best for |
|---|---|---|---|
| On-Demand | 0% | None | Short-term, unpredictable |
| Savings Plans (Compute) | Up to 66% | 1 or 3 years | Flexible steady workloads |
| Reserved Instance | Up to 72% | 1 or 3 years | Fixed instance type steady |
| Spot | Up to 90% | None | Fault-tolerant batch |