iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

A handful of AWS CLI patterns you reach for over and over - S3 sync, Lambda invoke, SSM, IAM policy testing, log tail.

AWS CLI by example

EXAMPLE
# 1. S3 sync - fast, idempotent, supports excludes
aws s3 sync ./dist s3://my-static-site \
  --delete \
  --exclude '*.map' \
  --cache-control 'public, max-age=31536000, immutable'

# Index files get short cache
aws s3 cp ./dist/index.html s3://my-static-site/index.html \
  --cache-control 'public, max-age=60' \
  --content-type 'text/html'


# 2. CloudFront invalidate after a deploy
aws cloudfront create-invalidation \
  --distribution-id ABCDEFGHIJ \
  --paths '/*'


# 3. Lambda invoke - synchronous, with file payload
aws lambda invoke \
  --function-name my-fn \
  --cli-binary-format raw-in-base64-out \
  --payload file://event.json \
  out.json && cat out.json


# 4. SSM session - SSH-less shell into an EC2 instance
aws ssm start-session --target i-0123456789abcdef0
# Requires the instance to have SSM agent + an IAM role with AmazonSSMManagedInstanceCore.


# 5. Parameter Store and Secrets Manager
aws ssm get-parameter --name /app/prod/db-url --with-decryption --query Parameter.Value --output text
aws secretsmanager get-secret-value --secret-id app/prod/db --query SecretString --output text | jq -r .password


# 6. Tail CloudWatch Logs live
aws logs tail /aws/lambda/my-fn --follow --since 5m
aws logs tail /aws/ecs/my-service --filter-pattern 'ERROR' --follow


# 7. IAM policy simulator
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::111111111111:role/MyRole \
  --action-names s3:GetObject \
  --resource-arns arn:aws:s3:::my-bucket/foo


# 8. STS assume role for a one-off action
aws sts assume-role \
  --role-arn arn:aws:iam::222222222222:role/CrossAccountRead \
  --role-session-name local-debug


# 9. Cost Explorer - last 7 days by service
aws ce get-cost-and-usage \
  --time-period Start=$(date -u -d '7 days ago' +%F),End=$(date -u +%F) \
  --granularity DAILY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE


# 10. Toolbelt
# aws configure list-profiles
# aws-vault exec prod -- aws s3 ls    # for short-lived MFA-backed sessions

Why it matters

These ten cover most of the daily AWS surface from the CLI. Use SSM Session Manager instead of SSH for instance access, use aws-vault for MFA-backed creds, and never paste long-lived access keys into a shell - even temporarily.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Tiny serverless web app: API Gateway -> Lambda -> DynamoDB. Hello, world.
Try it Yourself »

Discussion

Loading…