AWS CLI cheat sheet

Searchable AWS CLI reference: setup, S3, EC2, VPC/Route 53, CloudWatch, Lambda, ECR/ECS, IAM and CloudFormation, with every flag explained.

Runs in your browser ยท nothing is sentNew

48 commands

Setup & config

aws configureInteractively set your access key, secret key, default region and default output format.

Stores the values in ~/.aws/credentials and ~/.aws/config (or the equivalent on Windows). Run it once per machine, or use --profile to set up a second, named profile.

Options

--profile <name>Configure a named profile instead of the default one.
aws configure listShow the configuration values currently in effect and where each one came from (file, environment variable, or default).

Handy to confirm which profile, region and output format a command will actually use before running it, especially on a machine with several profiles or AWS_* environment variables set.

aws sts get-caller-identityShow the AWS account ID, user/role ARN and user ID that the current credentials belong to.

The quickest way to confirm which account and identity you are actually using before running something that matters, especially when switching between profiles.

aws <command> --profile <name>Run any command using a named profile instead of the default credentials.

Named profiles are defined in ~/.aws/credentials and ~/.aws/config, so you can keep separate credentials for different accounts without switching environment variables.

Example

aws s3 ls --profile prod
aws <command> --region <region>Run a command against a specific AWS Region, overriding the configured default.

Needed for any command whose resources are region-scoped (most services) when you want a region other than your profile default.

Example

aws ec2 describe-instances --region eu-west-1
aws <command> --output <format>Set the output format for a single command.

Options

jsonThe default. Easy to pipe into jq or other JSON tools.
textTab-separated plain text, convenient for shell scripting with cut/awk.
tableA human-readable ASCII table.
yamlYAML output.
yaml-streamStreamed YAML, one document per response page.
aws <command> --query "<JMESPath>"Filter and reshape the JSON response using a JMESPath expression, before it is even formatted for output.

Different from client-side filtering with --filters: --query runs after the AWS API responds and can pick, flatten or reshape any field, while --filters is sent to AWS and limits which items the API returns in the first place.

Example

aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId,State.State.Name]" --output table

S3

aws s3 ls [s3://bucket[/prefix]]List buckets (with no argument) or objects under a bucket and optional prefix.

Example

aws s3 ls s3://my-bucket/logs/ --recursive --human-readable --summarize

Options

--recursiveList every object under the prefix, not just the next folder level.
--human-readableShow sizes as KB/MB/GB instead of raw bytes.
--summarizeAdd a total object count and total size at the end.
aws s3 cp <source> <destination>Copy a single file or object, local-to-S3, S3-to-local, or S3-to-S3.

Example

aws s3 cp ./report.pdf s3://my-bucket/reports/ --storage-class STANDARD_IA

Options

--recursiveCopy an entire directory or prefix instead of a single file.
--storage-class <class>Storage tier for the uploaded object: STANDARD, STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING, GLACIER, DEEP_ARCHIVE, GLACIER_IR.
--sse [AES256|aws:kms]Enable server-side encryption on the uploaded object.
--acl <value>Set a canned ACL, for example public-read, private, bucket-owner-full-control.
--dryrunShow what would be copied without actually transferring anything.
aws s3 sync <source> <destination>Sync a local directory and an S3 prefix (in either direction), or two S3 prefixes, copying only new or changed files.

A file is transferred if its size differs, or if the source's last-modified time is newer than the destination's. Unlike cp, sync automatically skips files that already match.

Example

aws s3 sync ./dist s3://my-bucket/site --delete --exclude "*.map"

Options

--deleteDelete files at the destination that no longer exist at the source. Files excluded by a filter are not deleted.
--exclude "<pattern>"Skip files matching this pattern. Can be combined with --include to re-include a subset.
--include "<pattern>"Re-include files that a broader --exclude would otherwise skip.
--dryrunShow what would be transferred or deleted, without doing it. Always run this first with --delete.
--size-onlyCompare only file size, not modification time, to decide what to transfer.
--source-region <region>Region of the source bucket, when syncing between S3 buckets in different regions (--region then refers to the destination).
Careful: --delete removes destination files that are not in the source. Run with --dryrun first to see exactly what would be deleted before using it for real.
aws s3 rm s3://bucket/keyDelete a single object, or every object under a prefix with --recursive.

Example

aws s3 rm s3://my-bucket/old-logs/ --recursive --dryrun

Options

--recursiveDelete every object under the given prefix, not just an exact key match.
--dryrunShow what would be deleted without deleting it.
--exclude / --includeLimit a recursive delete to a subset of keys, same pattern syntax as sync.
Careful: There is no trash or undo for a deleted S3 object unless the bucket has versioning enabled. Always --dryrun a recursive delete first.
aws s3 mb s3://bucket-nameCreate a new, globally-unique-named bucket (mb = make bucket). Use "aws s3 rb" to remove one.

Example

aws s3 rb s3://my-bucket --force

Options

--forceOn rb (remove bucket): delete all objects in the bucket first, then the bucket itself.
Careful: "aws s3 rb --force" deletes every object in the bucket permanently before removing it.
aws s3 presign s3://bucket/key --expires-in <seconds>Generate a temporary, signed URL that grants time-limited access to a private object without needing AWS credentials.

Example

aws s3 presign s3://my-bucket/report.pdf --expires-in 3600

Options

--expires-in <seconds>How long the URL stays valid. Default is 3600 seconds (1 hour).

EC2

aws ec2 describe-instancesList EC2 instances and their full details (state, type, IPs, tags, security groups).

Example

aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].InstanceId"

Options

--instance-ids <id> [<id>...]Limit to specific instance IDs.
--filters "Name=<key>,Values=<value>"Server-side filter, for example instance-state-name, tag:Name, vpc-id. Reduces what AWS sends back, unlike --query which reshapes the response after the fact.
--query "<JMESPath>"Reshape the output, for example to a flat list of instance IDs.
aws ec2 start-instances --instance-ids <id>Start a stopped instance. Use "stop-instances" to stop a running one, or "reboot-instances" to restart it in place.

Options

--instance-ids <id> [<id>...]One or more instance IDs to act on.
--force (stop-instances only)Force-stop the instance without a clean shutdown; use only if a normal stop is not responding.
Careful: stop-instances on an instance using instance store (not EBS) loses any data on the instance store volumes.
aws ec2 terminate-instances --instance-ids <id>Permanently delete one or more EC2 instances.
Careful: This is destructive and, unless termination protection is enabled, cannot be undone: the instance and (by default) its root EBS volume are deleted.
aws ec2 describe-security-groupsList security groups and their inbound/outbound rules.

Example

aws ec2 describe-security-groups --group-ids sg-0123456789abcdef0

Options

--group-ids <id> [<id>...]Limit to specific security group IDs.
--filters "Name=<key>,Values=<value>"Filter by vpc-id, group-name, tag, and more.

Open AWS Security Group analyzer โ†’

aws ec2 create-key-pair --key-name <name> --query "KeyMaterial" --output text > <name>.pemCreate a new SSH key pair and save the private key to a local file.

The private key is only ever returned once, at creation time; AWS does not store a retrievable copy.

Careful: Set file permissions on the saved .pem file to be readable only by you (chmod 400 on Linux/macOS); SSH clients refuse overly permissive key files.

IAM

aws iam list-usersList every IAM user in the account.

Example

aws iam list-users --query "Users[].UserName"
aws iam list-attached-user-policies --user-name <user>List the managed policies directly attached to a user.

This does not show inline policies (use list-user-policies for those) or permissions granted through group membership (use list-groups-for-user, then check each group's attached policies).

aws iam get-policy-version --policy-arn <arn> --version-id <id>Show the JSON document for a specific version of a managed policy.

Find the current default version-id first with "aws iam get-policy --policy-arn <arn>".

Open IAM Policy analyzer โ†’

aws iam simulate-principal-policy --policy-source-arn <arn> --action-names <action>Ask AWS to evaluate, server-side, whether a user or role would be allowed to perform specific actions.

Example

aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123456789012:user/alice --action-names s3:GetObject --resource-arns arn:aws:s3:::my-bucket/*

Options

--action-names <action> [<action>...]One or more IAM actions to test, for example s3:GetObject.
--resource-arns <arn> [<arn>...]Limit the simulation to specific resources instead of "*".
aws iam create-access-key --user-name <user>Create a new access key (access key ID + secret) for a user.
Careful: The secret access key is shown only once and cannot be retrieved again. A user can have at most 2 access keys at a time; delete unused old ones.

CloudFormation

aws cloudformation deploy --template-file <file> --stack-name <name>Create or update a CloudFormation stack from a local template, waiting for the operation to finish.

Example

aws cloudformation deploy --template-file infra.yml --stack-name my-app --capabilities CAPABILITY_IAM --parameter-overrides Env=prod

Options

--capabilities <value>Required when the template creates IAM resources: CAPABILITY_IAM or CAPABILITY_NAMED_IAM.
--parameter-overrides <key=value> [...]Pass or override template parameters.
--no-execute-changesetCreate the change set and show what would change, without applying it.
aws cloudformation describe-stacks --stack-name <name>Show the status, parameters and outputs of a stack.

Leave out --stack-name to list every stack in the account and region.

aws cloudformation delete-stack --stack-name <name>Delete a stack and every resource it created, unless a resource has a DeletionPolicy of Retain.
Careful: This deletes all resources in the stack (databases, buckets with content, etc.) unless explicitly protected with a Retain or Snapshot deletion policy in the template.
aws cloudformation validate-template --template-body file://<file>Check a template for valid JSON/YAML syntax and structure before deploying it.

Only checks syntax and required fields; it does not check whether the resources it defines will actually succeed (quota limits, invalid property combinations, etc.).

VPC & Route 53

aws ec2 describe-vpcsList VPCs and their CIDR blocks, tenancy and default status.

Example

aws ec2 describe-vpcs --filters "Name=is-default,Values=true"

Options

--vpc-ids <id> [<id>...]Limit to specific VPC IDs.
--filters "Name=<key>,Values=<value>"Filter by cidr, is-default, tag:Name, and more.
aws ec2 describe-subnetsList subnets, their VPC, availability zone, CIDR block and available IP count.

Example

aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-0123456789abcdef0" --query "Subnets[].[SubnetId,CidrBlock,AvailabilityZone]"

Options

--filters "Name=vpc-id,Values=<id>"Limit to subnets within one VPC.

Open VPC/subnet planner โ†’

aws ec2 describe-route-tablesList route tables and their routes, including which subnets each table is associated with.

Useful for confirming whether a subnet is actually routed through a NAT gateway or internet gateway as expected, since a subnet associated with the wrong route table is a common source of "it should be private but isn't" surprises.

Example

aws ec2 describe-route-tables --filters "Name=vpc-id,Values=vpc-0123456789abcdef0"
aws ec2 describe-nat-gatewaysList NAT gateways, their state and the subnet/VPC they belong to.

A NAT gateway stuck in "pending" or "failed" state, or associated with the wrong subnet, is a common cause of private subnets losing outbound internet access.

aws route53 list-hosted-zonesList Route 53 hosted zones in the account.

Example

aws route53 list-hosted-zones --query "HostedZones[].[Name,Id]"
aws route53 list-resource-record-sets --hosted-zone-id <id>List the DNS records in a hosted zone.

Example

aws route53 list-resource-record-sets --hosted-zone-id Z0123456789ABCDEF --query "ResourceRecordSets[?Type=='MX']"
aws route53 change-resource-record-sets --hosted-zone-id <id> --change-batch file://<file>Create, update or delete DNS records in a hosted zone, from a JSON change-batch file.

There is no simpler single-record "set" subcommand; every change, including a single record, goes through a change-batch document describing one or more CREATE/UPSERT/DELETE actions.

Careful: A DELETE action in the change batch removes that exact record permanently. Always list-resource-record-sets first to confirm you are deleting the record you intend to.

CloudWatch & logs

aws logs tail <log-group> --followStream a CloudWatch Logs group to the terminal, similar to tail -f.

Example

aws logs tail /aws/lambda/my-function --follow --since 1h

Options

--followKeep streaming new log events as they arrive.
--since <duration>Only show events from this far back, for example 10m, 1h, 1d.
--filter-pattern "<pattern>"CloudWatch Logs filter pattern to narrow down which events are shown.
aws logs filter-log-events --log-group-name <name> --filter-pattern "<pattern>"Search a log group for events matching a filter pattern within a time range, without streaming.

A paginated operation: a single call returns at most 1 MB or 10,000 events, so the AWS CLI handles pagination automatically unless --no-paginate is set.

Example

aws logs filter-log-events --log-group-name /aws/lambda/my-function --filter-pattern "ERROR" --start-time 1700000000000

Options

--start-time / --end-time <epoch-ms>Time range to search, in epoch milliseconds.
--filter-pattern "<pattern>"CloudWatch Logs filter pattern (plain text or structured for JSON logs).
aws cloudwatch get-metric-statistics --namespace <ns> --metric-name <name> --start-time <iso> --end-time <iso> --period <seconds> --statistics AverageRetrieve a time series of a CloudWatch metric, for example CPU utilization or request count.

Example

aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-0123456789abcdef0 --start-time 2026-11-01T00:00:00Z --end-time 2026-11-02T00:00:00Z --period 300 --statistics Average

Options

--period <seconds>Granularity of each returned data point. Must be a valid CloudWatch period for the requested time range.
--statistics <stat> [<stat>...]Average, Sum, Minimum, Maximum, SampleCount.
--dimensions Name=<key>,Value=<value>Scope the metric to a specific resource.
aws cloudwatch describe-alarms --state-value ALARMList CloudWatch alarms, optionally filtered to only those currently in the ALARM state.

A quick way to see everything currently firing across an account/region without opening the console, useful at the start of an incident.

Lambda

aws lambda invoke --function-name <name> --payload <json> <output-file>Invoke a Lambda function directly from the CLI and save its response to a file.

Example

aws lambda invoke --function-name my-function --payload '{"key": "value"}' --cli-binary-format raw-in-base64-out response.json

Options

--invocation-type <RequestResponse|Event|DryRun>RequestResponse (default) waits for the result; Event invokes asynchronously and returns immediately; DryRun only validates permissions without running the function.
--payload <json-or-file>JSON input event. Use file://payload.json to read it from a file instead of inline.
--cli-binary-format raw-in-base64-outNeeded on AWS CLI v2 to pass --payload as raw JSON text instead of base64.
--log-type TailInclude the last 4 KB of the function's CloudWatch log output directly in the CLI response.
aws lambda list-functionsList Lambda functions in the account and region.

Example

aws lambda list-functions --query "Functions[].[FunctionName,Runtime,LastModified]" --output table
aws lambda update-function-code --function-name <name> --zip-file fileb://<file>.zipDeploy new code to an existing Lambda function from a local zip file.

Options

--zip-file fileb://<path>Local deployment package. The fileb:// prefix (as opposed to file://) is required for binary content like a zip.
--publishAlso publish a new numbered version after updating the code.
Careful: This immediately replaces the code running in $LATEST. For a safer rollout, publish a version and shift traffic gradually with an alias instead of updating $LATEST directly in production.
aws lambda update-function-configuration --function-name <name> --timeout <seconds> --memory-size <mb>Change a function's configuration (timeout, memory, environment variables, and more) without changing its code.

Example

aws lambda update-function-configuration --function-name my-function --environment "Variables={STAGE=prod}"
Careful: --environment replaces the entire set of environment variables, it does not merge with the existing ones. Read the current configuration first if you only want to add or change one variable.

ECR & ECS

aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <registry-url>Get a temporary authentication token for an ECR registry and feed it directly to docker login.

The token is valid for 12 hours. This replaced the older "aws ecr get-login" (which printed a whole docker login command) for better security, since the password no longer appears in shell history or process listings.

aws ecr describe-repositoriesList ECR container image repositories in the account.

Each repository has its own URI (registry/repository-name) used when tagging and pushing images with Docker.

aws ecr list-images --repository-name <name>List image tags and digests in a repository.

The example filters to untagged images, a common cleanup target since they still count toward storage but are not referenced by a tag.

Example

aws ecr list-images --repository-name my-app --query "imageIds[?imageTag==null]"
aws ecs list-services --cluster <cluster> aws ecs list-tasks --cluster <cluster> --service-name <service>List the services in an ECS cluster, then the running tasks for a specific service.

Both commands return ARNs; pass them to "aws ecs describe-services" / "aws ecs describe-tasks" for full detail, including the current deployment status and any stopped-task failure reason.

aws ecs update-service --cluster <cluster> --service <service> --force-new-deploymentTrigger a new deployment of an ECS service, for example to roll out a new image pushed under the same tag.

Options

--force-new-deploymentRedeploy even if the task definition has not changed, useful after pushing a new image to the same mutable tag.
--desired-count <n>Change the number of running tasks.
--task-definition <arn>Deploy a different (usually newer) task definition revision.
aws ecs execute-command --cluster <cluster> --task <task-id> --container <name> --interactive --command "/bin/sh"Open an interactive shell session inside a running ECS task container, similar to kubectl exec.

Requires ECS Exec to be enabled on the service/task definition and the Session Manager plugin installed locally.

The descriptions in this reference are currently in English.

About this tool

Search or filter by group and copy a command with one click. Open a command to see what it does, an example and every flag it takes, plus warnings for anything that deletes or terminates a resource.

๐Ÿ”’ Your input stays in your browser and is never sent anywhere.

Frequently asked questions

What is the difference between --query and --filters?

--filters is sent to AWS and limits which items the API returns. --query runs after the response comes back and reshapes it client-side with a JMESPath expression. They can be combined.

How do I tail Lambda logs from the CLI?

aws logs tail /aws/lambda/<function-name> --follow streams new log events as they arrive, similar to tail -f. Add --since 1h to also see recent history first.

What to do next

More in this section

Also useful

  • AWS Security Group analyzerPaste a describe-security-groups export to find open ports, redundant and shadowed rules, see a traffic diagram and the impact of removing a rule.
  • IAM Policy analyzerPaste an AWS IAM policy to find overly broad permissions, privilege escalation paths and confused-deputy risks, and simulate requests.
  • VPC/subnet plannerPlan subnets inside a VPC or VNet, see usable addresses after provider reservations, catch overlaps, and export Terraform or CloudFormation.
  • Audit script builderReady-made, read-only scripts and queries for SQL, Active Directory, AWS CLI and Azure CLI access reviews. Pick checks, copy the combined script.

Found a problem or have a suggestion? Tell us