AWS CLI commands

Command lines for AWS CLI version 2, checked against the AWS CLI 2.37.9 Command Reference and the version 2 User Guide and grouped by task: configuration, sign-in, S3, EC2, IAM, Lambda and logs, containers, CloudFormation, Systems Manager and secrets, DynamoDB, output control and global options. Every command has the shape aws, service, operation, and aws ec2 help lists what a service offers. Names such as amzn-s3-demo-bucket are the reference's sample values; rows that start with dashes are options to add to a command.

193 commands in 12 sections. Checked row by row against AWS CLI 2.37.9 Command Reference: aws s3 cp on . Edited by Jay.

Configuration and profiles 13

CommandWhat it does
aws configureSet up credentials interactivelyPrompts for access key, secret key, default Region and output format, then saves the answers under ~/.aws.
aws configure --profile profile-nameConfigure a named profileAsks the same questions but stores the answers under that profile name instead of the default profile.
aws configure listShow the active configurationLists profile, access key, secret key and Region together with where each value came from, such as an environment variable.
aws configure list-profilesList profile namesPrints the name of every profile the CLI finds in its configuration files.
aws configure get region --profile integRead one settingPrints the stored value; empty output means the setting is not set explicitly and its default applies.
aws configure set region us-west-2 --profile integChange one settingWrites the value into the named profile without opening the files; removing a setting still means editing them by hand.
aws configure import --csv file://credentials.csvImport credentials from a CSV fileReads the key file downloaded from the IAM console and creates a profile named after each user in it.
aws configure export-credentials --profile user1 --format envExport credentials as variablesPrints the profile's resolved credentials as shell export lines; without --format the result is the JSON process format.
aws configure ssoCreate an IAM Identity Center profileInteractive wizard for session name, start URL and Region that saves a profile drawing temporary credentials from Identity Center.
aws configure sso-sessionDefine an SSO sessionAsks for the session values only and stores them as an sso-session section that a profile can then be linked to.
aws configure mfa-loginGet temporary MFA credentialsAsks for the MFA device and token code, then writes short-lived credentials into a new profile.
aws configure add-model --service-model file://service.jsonAdd a service modelCopies the JSON model into ~/.aws/models so that commands for that service become available at once.
aws configure agent-toolkitSet up AI coding agentsWizard that detects installed coding agents, installs the default AWS skills and connects the AWS MCP Server.

Sign-in and identity 11

CommandWhat it does
aws loginSign in with console credentialsFetches temporary credentials from a Management Console session and renews them while the refresh token stays valid.
aws logoutSign out of a console loginRemoves what aws login cached for the profile in use; --all covers every profile that signs in this way.
aws sso login --profile my-dev-profileSign in to IAM Identity CenterOpens the default browser to confirm the sign-in, then caches the credentials that profile needs.
aws sso login --profile my-dev-profile --use-device-codeSign in with a device codeSwaps the default PKCE flow for device authorization, whose URL may be opened on a different device.
aws sso logoutDelete cached SSO credentialsRemoves the cached Identity Center tokens and the temporary credentials obtained with them.
aws sts get-caller-identityShow the current identityReturns the user ID, account and ARN behind the credentials the CLI is using right now.
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/xaccounts3access --role-session-name s3-access-exampleAssume an IAM roleReturns a temporary access key, secret key and session token for the role; the session name labels that session.
aws sts assume-role-with-web-identity --role-arn arn:aws:iam::123456789012:role/FederatedWebIdentityRole --role-session-name "app1" --web-identity-token TOKENAssume a role with a web tokenTrades a token from a web identity provider for short-term role credentials; the call itself needs no AWS credentials.
aws sts get-session-token --duration-seconds 900 --serial-number "YourMFADeviceSerialNumber" --token-code 123456Get MFA session credentialsReturns temporary credentials for the calling IAM user, valid here for 900 seconds, after the MFA code is checked.
aws sts decode-authorization-message --encoded-message MESSAGEDecode an authorization failureTurns the encoded text that came with a denied request into readable details about why it was refused.
aws sts get-access-key-infoFind an access key's accountGive the key with --access-key-id; the answer is the owning account ID and says nothing about whether the key is active.

S3 buckets and objects 26

The S3 preview flag is spelled --dryrun and prints the planned operations; the EC2 flag --dry-run is a different option that only checks permissions.

CommandWhat it does
aws s3 lsList your bucketsShows every bucket the user owns with its creation timestamp in the machine's time zone.
aws s3 ls s3://amzn-s3-demo-bucketList a bucket's contentsShows the objects and common prefixes directly under the bucket or prefix, not what lies deeper.
aws s3 ls s3://amzn-s3-demo-bucket --recursive --human-readable --summarizeList everything with totalsWalks all prefixes, prints sizes in readable units and ends with the object count and total size.
aws s3 cp test.txt s3://amzn-s3-demo-bucket/test2.txtUpload a fileCopies one local file to the given bucket and key, so the object can get a different name.
aws s3 cp s3://amzn-s3-demo-bucket/test.txt test2.txtDownload an objectFetches a single object and saves it under the local name given as the second argument.
aws s3 cp s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket2/Copy between bucketsCopies the object from one bucket into the other; the trailing slash keeps its original name.
aws s3 cp s3://amzn-s3-demo-bucket . --recursiveDownload a whole bucketWith --recursive every object under the bucket or prefix lands in the current directory.
aws s3 cp myDir s3://amzn-s3-demo-bucket/ --recursive --exclude "*.jpg"Upload a folder with exclusionsSends all files under the directory except those matching the excluded pattern.
aws s3 cp s3://amzn-s3-demo-bucket/logs/ s3://amzn-s3-demo-bucket2/logs/ --recursive --exclude "*" --include "*.log"Copy only matching objectsExcluding everything and then including one pattern leaves just the .log objects in the copy.
aws s3 cp - s3://amzn-s3-demo-bucket/stream.txtUpload from standard inputA dash in place of the source streams piped data into the object.
aws s3 mv test.txt s3://amzn-s3-demo-bucket/test2.txtMove a file into a bucketTakes the same arguments as cp, but the source no longer exists afterwards.
aws s3 rm s3://amzn-s3-demo-bucket/test2.txtDelete an object
aws s3 rm s3://amzn-s3-demo-bucket --recursiveEmpty a bucketDeletes every object under the bucket or prefix and leaves the bucket itself in place.
aws s3 sync . s3://amzn-s3-demo-bucketSync a folder to a bucketUploads only files that are new or whose size or modification time differs from the object in S3.
aws s3 sync s3://amzn-s3-demo-bucket .Sync a bucket to a folderDownloads the objects that are missing locally or differ in size or modification time.
aws s3 sync s3://amzn-s3-demo-bucket s3://amzn-s3-demo-bucket2Sync two bucketsCopies new and changed objects from the first bucket into the second.
aws s3 sync . s3://amzn-s3-demo-bucket --deleteSync and delete extrasAlso removes objects from the destination when they do not exist in the source directory.
--dryrunPreview without changesOn cp, mv, rm and sync it prints what the command would do and carries none of it out.
aws s3 mb s3://amzn-s3-demo-bucketCreate a bucketThe bucket is made in the Region from the user's configuration unless --region names another one.
aws s3 rb s3://amzn-s3-demo-bucketDelete an empty bucketFails while the bucket still holds objects.
aws s3 rb s3://amzn-s3-demo-bucket --forceDelete a bucket and its objectsRemoves the objects first and then the bucket; versioned objects stay behind, which makes the removal fail.
aws s3 presign s3://amzn-s3-demo-bucket/test2.txtCreate a pre-signed URLPrints a link to the object that stays valid for one hour, the default lifetime.
aws s3 presign s3://amzn-s3-demo-bucket/test2.txt --expires-in 604800Week-long pre-signed URLThe lifetime is given in seconds, and 604800 is the longest allowed.
aws s3 website s3://amzn-s3-demo-bucket/ --index-document index.html --error-document error.htmlTurn a bucket into a websiteSets the page served at the site root and the page shown on errors; file permissions are configured separately.
aws s3api head-object --bucket amzn-s3-demo-bucket --key index.htmlRead object metadataA low-level s3api call that returns the object's metadata and leaves its body where it is.
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket --versioning-configuration Status=EnabledTurn on bucket versioning

EC2 instances and networking 22

CommandWhat it does
aws ec2 describe-instances --instance-ids i-1234567890abcdef0Describe one instanceReturns the full record of the named instance; without the option every instance is described.
aws ec2 describe-instances --filters Name=instance-type,Values=m5.largeFilter instances by typeThe filter is applied by the service, so only matching instances come back.
aws ec2 describe-instances --filters "Name=tag:Owner,Values=my-team"Filter instances by tagThe tag: prefix followed by a key matches instances whose Owner tag carries that value.
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[*].Instances[*].[InstanceId]" --output textList matching instance IDsCombines a filter with a query and text output, which leaves nothing but the instance IDs.
aws ec2 start-instances --instance-ids i-1234567890abcdef0Start a stopped instanceWorks for EBS-backed instances that were stopped earlier.
aws ec2 stop-instances --instance-ids i-1234567890abcdef0Stop an instance
aws ec2 stop-instances --instance-ids i-1234567890abcdef0 --hibernateHibernate an instanceWorks only if hibernation was switched on for the instance and its prerequisites are met.
aws ec2 reboot-instances --instance-ids i-1234567890abcdef5Reboot an instance
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0Terminate an instanceCannot be undone: the instance is gone for good and volumes set to delete on termination go with it.
aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t2.micro --key-name MyKeyPairLaunch an instanceStarts one instance in the default subnet of the current Region; the key pair only matters for SSH or RDP access.
aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t2.micro --subnet-id subnet-08fc749671b2d077c --security-group-ids sg-0b0384b66d7d692f9 --associate-public-ip-address --key-name MyKeyPairLaunch into a chosen subnetPlaces the instance in a non-default subnet with the given security group and requests a public IP address.
aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t2.micro --count 1 --user-data file://my_script.txtLaunch with a startup scriptThe file's contents travel as user data and the script in it runs when the instance launches.
--dry-runCheck permissions onlyAccepted by EC2 commands: no request is made, and the error code tells whether you would have been allowed.
aws ec2 wait instance-running --instance-ids i-1234567890abcdef0Wait until an instance runsPrints nothing and returns once the instance is confirmed running, so a script can carry on.
aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0Check instance status
aws ec2 get-console-output --instance-id i-1234567890abcdef0 --latest --output textRead the console output--latest asks for the most recent output of the instance and text format prints it as plain lines.
aws ec2 describe-images --owners amazon --filters "Name=platform,Values=windows" "Name=root-device-type,Values=ebs"Find AMIs by owner and filterLists Windows images from Amazon that are backed by EBS; self as owner lists your own images.
aws ec2 create-key-pair --key-name MyKeyPairCreate a key pairEC2 stores the public key and prints the private key, which you have to save to a file yourself.
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-1a2b3c4dCreate a security groupCreates the group in the named VPC and returns its group ID.
aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --protocol tcp --port 22 --cidr 203.0.113.0/24Allow inbound SSHAdds a rule to the group that lets TCP port 22 in from the given address range.
aws ec2 describe-regions --all-regions --query "Regions[].{Name:RegionName}" --output textList all Region names--all-regions includes Regions that are disabled for the account; the query keeps just the names.
aws ec2 create-tags --resources ami-1234567890abcdef0 --tags Key=Stack,Value=productionTag a resourceAdds the tag, or replaces its value when the key is already present on the resource.

IAM users, roles and policies 13

CommandWhat it does
aws iam list-usersList IAM users
aws iam create-user --user-name BobCreate a user
aws iam delete-user --user-name BobDelete a userFrom the CLI the user's keys, policies and other attached items must be removed first, or the call fails.
aws iam create-access-key --user-name BobCreate an access keyReturns the new key ID together with its secret access key for the named user.
aws iam list-access-keys --user-name BobList a user's access keys
aws iam attach-user-policy --policy-arn arn:aws:iam::aws:policy/AdministratorAccess --user-name AliceAttach a policy to a userLinks an AWS managed policy, identified by its ARN, to the user.
aws iam list-rolesList IAM roles
aws iam get-role --role-name Test-RoleShow a role
aws iam create-role --role-name Test-Role --assume-role-policy-document file://Test-Role-Trust-Policy.jsonCreate a roleThe JSON file is the trust policy that says who may assume the role; permissions are attached separately.
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --role-name ReadOnlyRoleAttach a policy to a role
aws iam list-attached-role-policies --role-name SecurityAuditRoleList a role's managed policiesInline policies embedded in the role are not part of this list.
aws iam create-policy --policy-name my-policy --policy-document file://policy.jsonCreate a managed policyMakes a customer managed policy out of the JSON document, ready to attach to users, groups or roles.
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123456789012:user/alejandro --action-names codecommit:ListRepositoriesTest what a user may doEvaluates the user's policies against the named API action and reports whether it would be allowed or denied.

Lambda functions and logs 14

With AWS CLI version 2, a JSON payload typed on the command line needs --cli-binary-format raw-in-base64-out, as the invoke examples show.

CommandWhat it does
aws lambda list-functionsList Lambda functions
aws lambda get-function --function-name my-functionShow a functionReturns the function's details with a link for downloading the deployment package that works for ten minutes.
aws lambda invoke --function-name my-function --cli-binary-format raw-in-base64-out --payload '{ "name": "Bob" }' response.jsonInvoke a functionRuns it synchronously and writes the result to response.json; CLI version 2 needs the binary-format option here.
aws lambda invoke --function-name my-function --invocation-type Event --cli-binary-format raw-in-base64-out --payload '{ "name": "Bob" }' response.jsonInvoke asynchronouslyThe Event type hands the payload over without waiting for the function to finish.
--log-type TailInclude the execution logAn invoke option for synchronous calls; the response then carries the function's log.
aws lambda create-function --function-name my-function --runtime nodejs22.x --zip-file fileb://my-function.zip --handler my-function.handler --role arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-tges6bf4Create a functionUploads the zip as the code and sets runtime, handler and execution role in one call.
aws lambda update-function-code --function-name my-function --zip-file fileb://my-function.zipDeploy new codeSwaps in the zip's contents as the code of $LATEST, the unpublished version.
aws lambda update-function-configuration --function-name my-function --memory-size 256Change function settingsHere the memory of the unpublished $LATEST version becomes 256 MB.
aws lambda delete-function --function-name my-functionDelete a function
aws logs tail GROUP_NAME --followFollow a log group liveKeeps polling for new events until interrupted; without the flag it prints the past ten minutes and exits.
--since 5mStart further backA logs tail option that takes a relative time in seconds, minutes, hours, days or weeks, or an ISO 8601 timestamp.
--filter-patternShow matching events onlyA logs tail option: events that do not match the CloudWatch Logs pattern are left out.
aws logs describe-log-groups --log-group-name-prefix my-logsFind log groups by prefix
aws logs filter-log-eventsSearch a log groupLists events of one group, narrowed with --filter-pattern, --start-time and --end-time or a stream name prefix.

Container registries and clusters 22

CommandWhat it does
aws ecr get-login-passwordGet a registry passwordPrints an authentication token for the registry that stays valid for 12 hours.
aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin REGISTRYLog Docker in to ECRREGISTRY is the account ID, then .dkr.ecr., the Region and .amazonaws.com; name the Region the registry is in.
aws ecr create-repository --repository-name project-a/sample-repoCreate a repositoryThe name may carry a namespace in front of a slash, as project-a does here.
aws ecr describe-repositoriesList repositories
aws ecr list-images --repository-name cluster-autoscalerList image tags and digests
aws ecr describe-images --repository-name cluster-autoscaler --image-ids imageTag=v1.13.6Show image detailsReturns the metadata of the one image selected by its tag.
aws ecr batch-delete-image --repository-name ubuntu --image-ids imageTag=preciseDelete an image by tag
aws ecr delete-repository --repository-name ubuntu --forceDelete a repository--force is required as long as the repository still contains images.
aws ecs list-clustersList ECS clusters
aws ecs list-services --cluster MyClusterList services in a cluster
aws ecs describe-services --services my-http-serviceShow a serviceWith no --cluster given, the service is looked up in the default cluster.
aws ecs update-service --cluster test --service my-http-service --task-definition amazon-ecs-sampleDeploy a new task definitionSwitches the service over to the named task definition.
aws ecs update-service --cluster MyCluster --service my-http-service --desired-count 2Scale a serviceSets how many tasks the service should keep running.
--force-new-deploymentRedeploy without changesAn update-service option that starts a fresh deployment, for example to pick up a newer image under the same tag.
aws ecs execute-command --cluster MyCluster --task d789e94343414c25b9f6bd59eEXAMPLE --container MyContainer --interactive --command "/bin/sh"Open a shell in a containerRuns /bin/sh interactively in the named container of the task; the task may be given by ID or full ARN.
aws eks update-kubeconfig --name my-eks-clusterConnect kubectl to a clusterCreates or updates the kubeconfig entry for the cluster so that kubectl can reach it.
aws eks list-clustersList EKS clustersCovers the account's clusters in a single Region, the configured one unless --region says otherwise.
aws eks describe-cluster --name my-eks-clusterShow a cluster
aws eks create-cluster --name prod --role-arn arn:aws:iam::012345678910:role/eks-service-role-AWSServiceRoleForAmazonEKS-J7ONKE3BQ4PI --resources-vpc-config subnetIds=subnet-6782e71e,subnet-e7e761ac,securityGroupIds=sg-6979fe18Create a clusterCreates the cluster control plane with the given service role, subnets and security group.
aws eks delete-cluster --name my-eks-clusterDelete a clusterManaged node groups and Fargate profiles attached to the cluster have to be deleted first.
aws eks list-nodegroups --cluster-name my-eks-clusterList node groups
aws eks describe-nodegroup --cluster-name my-eks-cluster --nodegroup-name my-eks-nodegroupShow a node group

CloudFormation stacks 11

CommandWhat it does
aws cloudformation deploy --template-file /path_to_template/template.json --stack-name my-new-stack --parameter-overrides Key1=Value1 Key2=Value2 --tags Key1=Value1 Key2=Value2Deploy a templateCreates the stack when the name is new and updates it otherwise, by building and running a change set.
--no-execute-changesetCreate the change set onlyA deploy option: the change set is built for review and the command exits before applying it.
--capabilities CAPABILITY_IAMAcknowledge IAM resourcesA deploy option that has to be given when the template creates IAM users, roles or similar resources.
aws cloudformation package --template-file /path_to_template/template.json --s3-bucket bucket-name --output-template-file packaged-template.jsonPackage local artifactsUploads the local files the template refers to and writes a copy of the template pointing at their S3 locations.
aws cloudformation validate-template --template-body file://sampletemplate.jsonValidate a template
aws cloudformation describe-stacks --stack-name myteststackShow a stack
aws cloudformation describe-stack-events --stack-name my-stack --max-items 2Show recent stack eventsLimits the listing to the two most recent events of the stack.
aws cloudformation create-change-set --stack-name my-application --change-set-name my-change-set --template-body file://template.yaml --capabilities CAPABILITY_IAMCreate a change setPrepares the changes without applying them; the capability is needed because the template defines IAM resources.
aws cloudformation execute-change-set --change-set-name my-change-set --stack-name my-stackApply a change set
aws cloudformation wait stack-create-complete --stack-name my-stack-1234Wait for stack creationPauses the script and returns once CloudFormation confirms that the stack was created.
aws cloudformation delete-stack --stack-name my-stackDelete a stackThe command prints nothing when the deletion request is accepted.

Systems Manager and secrets 14

CommandWhat it does
aws ssm start-session --target "i-1234567890abcdef0"Open a session on an instanceInteractive Session Manager connection; the Session Manager plugin must be installed on the machine running the CLI.
aws ssm send-command --instance-ids "i-1234567890abcdef0" --document-name "AWS-RunShellScript" --comment "IP config" --parameters "commands=ifconfig"Run a command on an instanceExecutes the shell command through the AWS-RunShellScript document on the listed instance.
aws ssm get-command-invocation --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" --instance-id "i-1234567890abcdef0"Read a command's resultShows the status and the standard output of that command on that instance.
aws ssm describe-instance-informationList managed instances
aws ssm get-parameter --name "MyStringParameter"Read a parameter
aws ssm get-parameter --name "MySecureStringParameter" --with-decryptionRead a decrypted parameterThe flag makes Parameter Store return a SecureString value in decrypted form.
aws ssm get-parameters-by-path --path "/site/newyork/department/"List parameters under a pathReturns the parameters in that hierarchy; --recursive also walks every level below it.
aws ssm put-parameter --name "MyStringParameter" --type "String" --value "Vici" --overwriteSet a parameter--overwrite is what allows the value of an existing parameter to be replaced.
aws ssm put-parameter --name "/Finance/Payroll/q2accesskey" --value "P@sSwW)rd" --type "SecureString"Store an encrypted parameterSecureString is the type for sensitive values; the reference example also sets the Advanced tier and an expiry policy.
aws secretsmanager get-secret-value --secret-id MyTestSecretRead a secretReturns the current version of the secret unless a version ID or staging label is given.
aws secretsmanager create-secret --name MyTestSecret --secret-string file://mycreds.jsonCreate a secret from a fileThe file:// prefix loads the secret text, here a set of credentials, from the JSON file.
aws secretsmanager put-secret-value --secret-id MyTestSecret --secret-string file://mycreds.jsonStore a new secret version
aws secretsmanager list-secretsList secretsReturns names and details of the account's secrets, never the secret values themselves.
aws secretsmanager delete-secret --secret-id MyTestSecret --recovery-window-in-days 7Schedule a secret for deletionUntil the date in the DeletionDate field the secret can still be brought back with restore-secret.

DynamoDB tables and items 8

CommandWhat it does
aws dynamodb list-tablesList tablesCovers the tables of the current account and Region.
aws dynamodb describe-table --table-name MusicCollectionShow a table
aws dynamodb create-table --table-name MusicCollection --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE --billing-mode PAY_PER_REQUESTCreate an on-demand tableArtist becomes the hash key and SongTitle the range key; on-demand mode replaces provisioned throughput.
aws dynamodb put-item --table-name MusicCollection --item file://item.jsonAdd an itemThe new item's attributes are read from the JSON file.
aws dynamodb get-item --table-name MusicCollection --key file://key.jsonRead an item by keyThe key file must hold every primary key attribute, here both Artist and SongTitle.
aws dynamodb delete-item --table-name MusicCollection --key file://key.json --return-values ALL_OLDDelete an itemALL_OLD makes the response include the item as it was before it was removed.
aws dynamodb query --table-name MusicCollection --projection-expression "SongTitle" --key-condition-expression "Artist = :v1" --expression-attribute-values file://expression-attributes.jsonQuery by hash keyOnly the hash key value is given, so every song title of that one artist is returned.
aws dynamodb scan --table-name MusicCollection --filter-expression "Artist = :a" --projection-expression "#ST, #AT" --expression-attribute-names file://expression-attribute-names.json --expression-attribute-values file://expression-attribute-values.jsonScan a table with a filterReads the entire table first and only then narrows the result to the items that pass the filter.

Output format and filtering 18

With --output text a --query runs on each page of results separately and can return more than expected; with json or yaml it runs once on the whole response.

CommandWhat it does
--output jsonOutput as JSONThe whole response is treated as one structure, so a --query runs once against all of it.
--output yamlOutput as YAML
--output textOutput as plain textFields are separated by tabs, one record per line, which suits grep, awk and similar tools.
--output tableOutput as a tableDraws the result as a bordered table meant for reading rather than for scripts.
--output offSuppress standard outputNothing is printed on success, so a script checks the exit code only; errors still reach stderr.
--queryFilter the responseTakes a JMESPath expression that the CLI applies on the client after the service has answered.
aws ec2 describe-volumes --query 'Volumes[0]'Select the first elementAn index in square brackets picks one entry from a list, counting from zero.
aws ec2 describe-volumes --query 'Volumes[*].Attachments[].State'Flatten nested listsThe empty brackets merge the per-volume lists into a single list of states.
aws ec2 describe-volumes --query 'Volumes[*].Attachments[?State==`attached`].VolumeId'Filter by a field valueThe [? ] test keeps only the attachments whose state equals the literal written in backticks.
aws ec2 describe-volumes --query 'Volumes[].[VolumeId, VolumeType]'Pick several fieldsEach volume is reduced to a short list holding just those two values.
aws ec2 describe-volumes --query 'Volumes[].{VolumeType: VolumeType}'Label the selected fieldsCurly braces build an object for each item, with the word before the colon as its key.
aws ec2 describe-images --owners self --query 'reverse(sort_by(Images,&CreationDate))[:5].{id:ImageId,date:CreationDate}'Show the five newest AMIsSorts your own images by creation date, reverses the order and keeps the first five.
aws ec2 describe-volumes --filters "Name=availability-zone,Values=us-west-2a" "Name=status,Values=attached" --query 'Volumes[?Size > `50`].{Id:VolumeId,Size:Size,Type:VolumeType}'Combine filters and a queryThe service applies --filters first; the query then keeps the volumes larger than 50 from what was sent back.
--no-cli-pagerPrint without the pagerSends the output of this one command straight to the terminal instead of through less or more.
--no-paginateFetch only the first pageThe CLI makes a single call instead of following the pagination tokens to the end.
--page-size 100Request smaller pagesEverything is still retrieved, but in smaller calls, which helps when a large listing times out.
--max-items 100Limit the items returnedOutput stops after that many items and carries a NextToken for picking up where it ended.
--max-items 100 --starting-token TOKENContinue from a tokenPass the NextToken value from the previous output to get the following batch of items.

Global options and environment variables 21

Input files and skeletons work with the commands generated from service APIs, not with custom commands such as aws s3.

CommandWhat it does
aws s3 ls --profile profile1Use a named profile--profile runs this one command with the credentials and settings stored under that profile.
aws ec2 describe-instances --output table --region us-west-1Run against another Region--region overrides the configured Region for a single command, here to look for an instance elsewhere.
aws s3 ls --endpoint-url http://localhost:4567Send requests to another URLReplaces the endpoint the CLI would work out from the service and Region with a custom one.
aws servicename commandname options --debug 2> debug.txtWrite debug logs to a file--debug adds the full Python logs on stderr, and the redirect collects that stream in a file.
--no-verify-sslSkip certificate checksTurns off SSL certificate verification for the command; AWS marks this as not best practice.
--no-sign-requestSend unsigned requestsRequests go out without a signature and no credentials are loaded at all.
--cli-auto-promptPrompt for the commandOpens the interactive prompt, which suggests commands, parameters and resource names as you type.
aws ec2 run-instances --generate-cli-skeleton input > ec2runinst.jsonGenerate an input templateWrites a JSON file with every parameter of the command, to be trimmed and filled in by hand.
aws ec2 run-instances --cli-input-json file://ec2runinst.jsonRun from a JSON input fileReads the parameters from the file; the custom aws s3 commands do not support this.
aws --versionShow the installed versionPrints the CLI version with the Python and operating system versions; the usual check after installing.
aws helpOpen the top-level helpCovers the general options and the list of available top-level commands.
aws ec2 helpList a service's commands
aws ec2 describe-instances helpOpen help for one commandDescribes the input parameters, filters and output of that operation and shows examples.
AWS_PROFILEChoose the profile by variableReplaces the [default] profile for every command in the shell; --profile on a command still wins.
AWS_REGIONChoose the Region by variableTakes precedence over AWS_DEFAULT_REGION and the profile's region setting, and yields to --region.
export AWS_DEFAULT_REGION=us-west-2Set a variable on Linux or macOSThe value lasts until the shell session ends or the variable is set again.
setx AWS_DEFAULT_REGION us-west-2Set a variable in Command PromptApplies to the current Command Prompt and to those opened later, not to shells that are already running.
AWS_DEFAULT_OUTPUTChoose the output format by variableOverrides the output setting of the profile and is itself overridden by --output.
AWS_PAGERChoose or disable the pagerNames the pager program; an empty string switches paging off altogether.
AWS_ACCESS_KEY_IDSupply the access keyOverrides aws_access_key_id from the profile; there is no command line option for it.
AWS_SECRET_ACCESS_KEYSupply the secret keyGoes together with AWS_ACCESS_KEY_ID and overrides aws_secret_access_key from the profile.

Notes

Identity first

aws configure stores an access key, secret key, Region and output format in ~/.aws; profiles (--profile name) keep several accounts separate. aws sts get-caller-identity prints the account and IAM identity the CLI is currently using, which makes it the command to run before anything else when a call returns AccessDenied: it shows at once whether the wrong profile is active. aws configure list adds where each setting came from. IAM Identity Center logins use aws sso login --profile my-dev-profile and then work with the same commands.

S3

aws s3 ls lists buckets, and with a bucket name lists objects. aws s3 cp [src] [dst] copies a file or, with --recursive, a tree in either direction, and aws s3 sync [src] [dst] copies only what changed — the command for deploying a static site or mirroring a backup, and --delete also removes destination files that no longer exist in the source. --dryrun prints what any of these would do without doing it. The s3 commands are high-level; s3api exposes every raw operation when a flag is missing.

Compute and deployment

aws ec2 describe-instances lists instances with their state and IPs — pair it with --query (JMESPath) and --output table to make it readable. aws ecs list-services and aws lambda list-functions inventory services and functions in the current Region. aws cloudformation deploy creates the stack when its name is new and updates it otherwise, by building and executing a change set; with --no-execute-changeset it stops after creating the change set so that it can be reviewed first.

Questions

How do I check which AWS account the CLI is using?

Run aws sts get-caller-identity: it returns the user ID, the account and the ARN behind the credentials in use. aws configure list shows the active profile, keys and Region and where each value comes from.

What is the difference between aws s3 cp and aws s3 sync?

cp copies exactly what you name: one file, or a whole tree with --recursive. sync compares source and destination and transfers only files that are new or differ in size or modification time; with --delete it also removes destination files that are missing from the source.

How do I log Docker in to Amazon ECR?

Pipe the registry password into docker login: aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin REGISTRY, where REGISTRY is your account ID followed by .dkr.ecr., the Region and .amazonaws.com. The token is valid for 12 hours.

How do I stop the AWS CLI from opening a pager?

Add --no-cli-pager to a single command. To switch the pager off for every command, set the AWS_PAGER environment variable or the cli_pager setting to an empty string.

Which output formats does the AWS CLI support?

json, yaml, yaml-stream, text, table and off. Choose one per command with --output, for example --output table, or set a default with the output setting of a profile or the AWS_DEFAULT_OUTPUT variable.

Sources and checks

117 more source pages

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.