10 Most Useful AWS CLI Commands for DevOps

The 10 AWS CLI v2 commands DevOps engineers use most, with script-safe flags, --query examples, waiters and CI tips for EC2, S3, EKS, ECR and Lambda.

Dec 22, 2025 - 12:19
Nov 11, 2026 - 05:08
 0  77
10 Most Useful AWS CLI Commands for DevOps

The most useful AWS CLI commands for DevOps work are aws sts get-caller-identity, aws ec2 describe-instances, aws s3 sync, aws cloudformation deploy, aws ecr get-login-password, aws eks update-kubeconfig, aws logs tail, aws ssm start-session, aws ssm get-parameter and aws lambda update-function-code. Together they cover identity checks, inventory, artifacts, infrastructure, containers, logs and deployments.

Most cheat sheets list commands by service. This guide groups them by the job you are doing in a pipeline or during an incident, shows the flags that make each one script friendly, and explains what can go wrong. All syntax below is for AWS CLI version 2 and was checked against the AWS CLI Command Reference. If you are preparing for interviews, pair this page with our AWS DevOps interview questions.

Key takeaways

  • Run aws sts get-caller-identity before anything destructive. It tells you which account and role the CLI is really using.
  • Learn --query (JMESPath) and --output. They turn long JSON into one value a shell script can use.
  • Prefer short-lived credentials from IAM Identity Center (aws sso login) or OIDC roles in CI over long-lived access keys.
  • Use aws ec2 wait, aws lambda wait and similar waiters instead of sleep loops in pipelines.
  • aws s3 sync --delete and terminate-instances remove things for good. Add --dryrun or --dry-run first.
  • Session Manager (aws ssm start-session) gives shell access without opening port 22 or handling SSH keys.

Set up the CLI the way a pipeline expects

Install version 2 from the official installer, then decide how credentials reach it. On a laptop, configure a named profile linked to IAM Identity Center:

aws configure sso          # one-time wizard, writes a profile to ~/.aws/config
aws sso login --profile dev
export AWS_PROFILE=dev

In CI, avoid storing access keys as secrets where you can. GitHub Actions, GitLab CI and others can exchange an OIDC token for a short-lived role session. The CLI reads the standard environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION) that those integrations set. Two more settings matter for scripts:

  • AWS_PAGER="" stops the CLI from opening a pager, which would hang a non-interactive job.
  • --output json (or text for single values) keeps output predictable regardless of a user's default.

The 10 commands at a glance

#CommandJob it doesRisk level
1aws sts get-caller-identityConfirm account and roleRead only
2aws ec2 describe-instancesInventory and filteringRead only
3aws s3 syncShip static sites and artifactsCan delete objects
4aws cloudformation deployCreate or update stacksChanges infrastructure
5aws ecr get-login-passwordDocker login to ECRIssues a 12-hour token
6aws eks update-kubeconfigConnect kubectl to EKSEdits kubeconfig
7aws logs tailFollow CloudWatch LogsRead only
8aws ssm start-session / send-commandShell and remote commands without SSHRuns commands on hosts
9aws ssm get-parameter / secretsmanager get-secret-valueRead config and secretsExposes secrets in output
10aws lambda update-function-codeDeploy function codeChanges production code

1. aws sts get-caller-identity: know who you are

This returns the account ID, user or role ARN and user ID for the credentials in use. It needs no IAM permission, so it works even with a tightly scoped role. Put it at the top of every deployment script so the log shows which account the job touched.

aws sts get-caller-identity --query Account --output text
# 123456789012

A simple guard stops a script from running against the wrong account:

expected="123456789012"
actual=$(aws sts get-caller-identity --query Account --output text)
[ "$actual" = "$expected" ] || { echo "Wrong account: $actual"; exit 1; }

2. aws ec2 describe-instances: inventory with filters and queries

The raw output is long. Server-side --filters cut the result set before it reaches you; client-side --query picks fields. Use both.

aws ec2 describe-instances \
  --filters "Name=tag:Environment,Values=staging" "Name=instance-state-name,Values=running" \
  --query "Reservations[].Instances[].[InstanceId,PrivateIpAddress,Tags[?Key=='Name']|[0].Value]" \
  --output table

Related commands you will use with it:

  • aws ec2 stop-instances --instance-ids i-0abc... and start-instances for scheduled shutdowns of non-production hosts.
  • aws ec2 wait instance-running --instance-ids i-0abc... blocks until the state changes, which is safer than a fixed sleep.
  • --dry-run on EC2 actions checks permissions without making the change.

The CLI paginates automatically for most list calls. For very large accounts, --page-size reduces the size of each API call so you avoid timeouts, while still returning every result.

3. aws s3 sync: publish builds and static sites

aws s3 sync copies only new or changed files, so it is the usual last step for a static front end or a folder of build artifacts.

aws s3 sync ./dist s3://my-site-bucket/ --delete --dryrun   # preview
aws s3 sync ./dist s3://my-site-bucket/ --delete \
  --cache-control "public,max-age=300"

--delete removes objects in the bucket that are not in the local folder. Run with --dryrun once, and turn on bucket versioning so a bad sync can be rolled back. For a single file, aws s3 cp is simpler. To share a private object for a short time, aws s3 presign s3://bucket/key --expires-in 3600 creates a temporary URL.

If a CloudFront distribution sits in front of the bucket, follow the sync with aws cloudfront create-invalidation --distribution-id E123... --paths "/index.html". Invalidate only files whose names stay the same between builds (such as index.html); assets with hashed file names do not need it.

4. aws cloudformation deploy: one command for create and update

deploy creates a change set and executes it, and it handles both new and existing stacks. That makes it easier to script than create-stack plus update-stack.

aws cloudformation deploy \
  --template-file infra/app.yaml \
  --stack-name app-staging \
  --parameter-overrides Env=staging ImageTag=$GIT_SHA \
  --capabilities CAPABILITY_NAMED_IAM \
  --no-fail-on-empty-changeset

Notes for pipelines:

  • --capabilities is required when the template creates IAM resources. Without it the deploy fails by design.
  • --no-fail-on-empty-changeset stops a re-run with no changes from breaking the job.
  • Add --no-execute-changeset to create the change set for review only, then approve it in a later stage.
  • If your template uses local code paths (Lambda, nested stacks), run aws cloudformation package first to upload them to S3.

When a deploy fails, aws cloudformation describe-stack-events --stack-name app-staging --max-items 20 shows the resource that broke. Teams using Terraform instead will find the equivalent workflow in our AWS vs Azure vs GCP DevOps tools comparison.

5. aws ecr get-login-password: push images from CI

This prints an authorization token that is valid for 12 hours, which you pipe straight into Docker so it never appears in logs.

REGISTRY=123456789012.dkr.ecr.ap-south-1.amazonaws.com
aws ecr get-login-password --region ap-south-1 \
  | docker login --username AWS --password-stdin "$REGISTRY"
docker push "$REGISTRY/web:$GIT_SHA"

The older aws ecr get-login command was removed in CLI version 2, so old scripts that call it will fail after an upgrade. After a push, aws ecr describe-image-scan-findings --repository-name web --image-id imageTag=$GIT_SHA reads scan results if scanning is enabled on the repository.

6. aws eks update-kubeconfig: connect kubectl to a cluster

This adds or updates a context in ~/.kube/config that uses the CLI to fetch a token for EKS.

aws eks update-kubeconfig --region ap-south-1 --name prod-cluster --alias prod
kubectl config current-context
kubectl get nodes

If kubectl then returns "Unauthorized", the CLI identity is not mapped to Kubernetes permissions. On current EKS versions that is done with access entries (aws eks list-access-entries --cluster-name prod-cluster) or the older aws-auth ConfigMap. Once connected, our list of kubectl commands DevOps engineers use daily picks up where this one stops.

7. aws logs tail: follow CloudWatch Logs in the terminal

Added in version 2, logs tail replaces clicking through log streams in the console.

aws logs tail /aws/lambda/orders-api --follow --since 15m --filter-pattern ERROR

--since accepts relative values such as 10m or 2h, and --format short trims the output. For questions across many log groups, CloudWatch Logs Insights can be started from the CLI with aws logs start-query and read back with aws logs get-query-results.

8. aws ssm start-session and send-command: access hosts without SSH

AWS Systems Manager Session Manager opens a shell on an instance through the SSM agent. You need the Session Manager plugin installed locally and an instance role that allows SSM, but no inbound port 22 and no key pairs. Sessions can be logged to S3 or CloudWatch for audit.

aws ssm start-session --target i-0abc1234def567890

To run the same command on many instances, use Run Command with tag targeting:

aws ssm send-command \
  --document-name "AWS-RunShellScript" \
  --targets "Key=tag:Role,Values=web" \
  --parameters 'commands=["systemctl status nginx --no-pager"]' \
  --comment "nginx status check"

Read the results with aws ssm list-command-invocations --command-id <id> --details. Removing SSH from your security groups is one of the simplest ways to shrink attack surface, a point our post on open network ports covers in more depth.

9. aws ssm get-parameter and secretsmanager get-secret-value: read config at deploy time

Parameter Store holds configuration and, as SecureString, encrypted values. Secrets Manager adds rotation for credentials such as database passwords.

aws ssm get-parameter --name /app/staging/db_host --query Parameter.Value --output text
aws ssm get-parameter --name /app/staging/api_key --with-decryption --query Parameter.Value --output text
aws secretsmanager get-secret-value --secret-id prod/orders/db --query SecretString --output text

These commands print secrets to standard output. In CI, assign them to a masked variable rather than echoing them, and give the pipeline role read access only to the paths it needs. Our guide to managing secrets in DevOps goes further.

10. aws lambda update-function-code: deploy a function

aws lambda update-function-code --function-name orders-api \
  --zip-file fileb://build/function.zip --publish
aws lambda wait function-updated --function-name orders-api
aws lambda update-alias --function-name orders-api --name live --function-version 7

The fileb:// prefix tells the CLI to read binary content. The waiter matters: a configuration update sent while the previous code update is still in progress fails with a conflict error. Publishing a version and moving an alias gives you a one-command rollback (point the alias back). For a quick test, aws lambda invoke --function-name orders-api --payload '{}' --cli-binary-format raw-in-base64-out out.json runs the function and writes the response to a file.

Making AWS CLI scripts safe for production

HabitHowWhy
Fail fastset -euo pipefail at the top of bash scriptsA failed CLI call stops the script instead of continuing with empty variables
Pin the region--region or AWS_REGION in the jobAvoids surprises from a developer's default profile
Preview changes--dry-run (EC2), --dryrun (S3), --no-execute-changeset (CloudFormation)Catches permission errors and unwanted deletes
Wait, do not sleepaws <service> wait ...Waiters poll the real state and time out cleanly
Least privilegeOne IAM role per pipeline, scoped to its resourcesLimits damage if CI credentials leak
Skeletons--generate-cli-skeleton and --cli-input-json / --cli-input-yamlKeeps complex requests in reviewed files

When an error message is unclear, add --debug to see the HTTP request, the credential source the CLI picked and the API response. It is the quickest way to find out that a script picked up the wrong profile.

Practise these commands safely

Use a sandbox account, tag everything you create, and finish each lab by listing and deleting resources. The EC2, S3, IAM and Lambda interview questions post is a good self-test once the commands feel familiar, and how AWS Auto Scaling works explains the service behind many of the instance commands above. If you want guided labs on pipelines, CloudFormation and EKS, see our AWS Certified DevOps Engineer Professional training (classroom in Kharadi, Pune, or live online), or start with the Solutions Architect Associate course if AWS is new to you.

Frequently asked questions

What is the difference between AWS CLI version 1 and version 2?

Version 2 is the current major version. It ships as a standalone installer with its own Python runtime and adds IAM Identity Center (SSO) support, aws logs tail, auto-prompt and a default pager. Some version 1 commands, such as aws ecr get-login, were removed.

How do I see only one value from an AWS CLI command?

Use --query with a JMESPath expression and --output text. For example, aws sts get-caller-identity --query Account --output text prints only the account ID, which you can store in a shell variable.

Should I use access keys with the AWS CLI in CI/CD?

Avoid long-lived keys where possible. Most CI platforms can assume an IAM role through OIDC and receive short-lived credentials for each job. On laptops, IAM Identity Center profiles with aws sso login do the same job.

How do I stop the AWS CLI from hanging in a script?

Version 2 opens a pager for long output by default. Set AWS_PAGER="" in the environment or pass --no-cli-pager so non-interactive jobs never wait for input.

Is aws s3 sync safe to use with --delete?

It deletes bucket objects that are missing locally, so run it once with --dryrun and enable versioning on the bucket. Versioning lets you recover objects removed by a mistaken sync.

How do I connect to an EC2 instance without SSH?

Use aws ssm start-session --target <instance-id>. The instance needs the SSM agent and an instance profile that allows Systems Manager, and your machine needs the Session Manager plugin. No inbound port is required.

Why does aws lambda update-function-configuration fail right after a code update?

Lambda allows one update at a time per function. Run aws lambda wait function-updated --function-name <name> between the two calls so the second starts only after the first completes.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.