123DevOps··10 min read

How to manage AWS with the AWS CLI: sign-in, profiles, queries, and safe scripts

Install the AWS CLI v2, authenticate without long-lived keys (aws login, IAM Identity Center, and assume role), and master daily recipes for EC2, S3, IAM, tags, costs, and logs with --query, waiters, and --dry-run.

Cloud

The AWS console is great for discovering things. For day-to-day administration, though, the AWS CLI wins: it is repeatable, it goes into scripts, it lands in your terminal history, and it shows exactly which API call you made. In this guide we install the CLI v2, authenticate without long-lived access keys, and build a toolkit of commands for EC2, S3, IAM, tags, costs, and logs. At the end, a script that walks through every Region.

The commands and flags in this post were checked against the offline help of AWS CLI 2.42.1 (aws <service> <command> help). The EC2, S3, IAM, tag, and log recipes also ran against a local AWS mock (moto), without touching a real account. If you are not yet comfortable in the terminal, start with how to use the terminal.

Installing with the signed script

The recommended method today is a signed one-line installer (PGP on macOS and Linux, Authenticode on Windows). It works on x86_64 and ARM and, by default, installs for your user only, in $HOME/.local/share/aws-cli, with the shortcut in $HOME/.local/bin:

# macOS and Linux, current user only
curl -fsSL https://awscli.amazonaws.com/v2/install.sh | bash

# for all users (/usr/local/aws-cli and /usr/local/bin)
curl -fsSL https://awscli.amazonaws.com/v2/install.sh | sudo bash -s -- --system

aws --version
# Windows PowerShell, current user
irm https://awscli.amazonaws.com/v2/install.ps1 | iex

The classic installers (.pkg on macOS, .zip on Linux, .msi on Windows) are still documented. The same one-line command also handles updates.

Authentication without long-lived keys

The rule is simple: do not create IAM user access keys for human use. A key that never expires ends up in .bash_history, in a repository, or on a stolen laptop. The modern CLI works with temporary credentials that renew themselves.

Method For whom Credential Command
aws login Anyone who already signs in to the console (root, IAM user, or federated) Temporary, renewed from the console session aws login
IAM Identity Center Companies with many accounts and SSO Temporary, per account and permission set aws sso login
Assume role Switching accounts or elevating privilege Temporary, through STS profile with role_arn
Machine role EC2, ECS, Lambda, CI with OIDC Temporary, delivered by the service none (automatic)

aws login: your console credentials in the terminal

aws login is the newest path (CLI 2.32.0 or later). It opens the browser, uses your console session, and returns temporary credentials plus a refresh token. The CLI renews the credentials on its own (every 15 minutes, for up to 12 hours or the identity’s session limit). The IAM identity needs the SignInLocalDevelopmentAccess managed policy.

aws login                    # writes login_session and the Region to ~/.aws/config
aws login --profile dev
aws login --remote           # machine without a browser (SSH): paste the authorization code
aws logout

IAM Identity Center

If your company uses AWS Organizations, IAM Identity Center (formerly AWS SSO) is the standard. The docs recommend aws configure sso for these users. The wizard creates an sso-session section and one profile per account and permission set. After that, you just sign in again when the session expires:

aws configure sso
aws sso login --profile dev            # authorization code flow with PKCE
aws sso login --profile dev --use-device-code   # older device code flow

Profiles, AWS_PROFILE, and assume role

A realistic ~/.aws/config ties it all together: an SSO session, a development profile, and an administrative profile that assumes a role using the SSO profile as its source.

[sso-session your-org]
sso_start_url = https://your-org.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access

[profile dev]
sso_session = your-org
sso_account_id = 123456789012
sso_role_name = PowerUserAccess
region = sa-east-1
output = json

[profile admin]
role_arn = arn:aws:iam::123456789012:role/OrgAdmin
source_profile = dev
role_session_name = admin-cli
duration_seconds = 3600
region = us-east-1

Pick the profile with --profile admin or export AWS_PROFILE=admin in your shell session. On AWS machines, replace source_profile with credential_source = Ec2InstanceMetadata (or EcsContainer). Environment variables such as AWS_REGION take precedence over the files, which is handy in CI (see environment variables and the 12-factor app).

Who am I?

Before any destructive command, confirm the account and identity. It is even worth an alias:

aws sts get-caller-identity --output table
aws configure list           # shows where the profile, Region, and credentials come from

Output, --query, and pagination

--query applies a JMESPath expression on the client, after the response arrives. --filters, on the other hand, filters on the server and reduces what travels over the wire. Use both together.

--output When to use it
json Default; ideal for jq and for saving responses
table Quick human reading in the terminal
text Scripts with read, cut, for (tab-separated)
yaml / yaml-stream Reading nested structures and config files
off Recent versions: only the exit code matters

Pagination is automatic: the CLI makes as many calls as needed. To take control, use --max-items with --starting-token, --page-size for smaller pages (avoids timeouts on large lists), or --no-paginate for the first page only.

Daily recipes

EC2: list, stop, and start safely

aws ec2 describe-instances \
  --filters Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].{ID:InstanceId,Type:InstanceType,AZ:Placement.AvailabilityZone,Name:Tags[?Key==`Name`]|[0].Value}' \
  --output table

aws ec2 stop-instances --instance-ids i-0123456789abcdef0 --dry-run
aws ec2 stop-instances --instance-ids i-0123456789abcdef0
aws ec2 wait instance-stopped --instance-ids i-0123456789abcdef0
aws ec2 start-instances --instance-ids i-0123456789abcdef0
aws ec2 wait instance-running --instance-ids i-0123456789abcdef0

--dry-run tests the permission without running the action: a DryRunOperation response means “it would have worked,” and UnauthorizedOperation means a permission is missing. The command exits with an error in both cases, so do not chain it with &&. Waiters poll every 15 seconds and give up after 40 attempts, with exit code 255.

S3: s3 sync or s3api?

The aws s3 commands (cp, mv, rm, sync, ls, mb, rb, presign) are high level: they handle multipart, parallelism, and file comparison for you. The aws s3api commands map 1:1 to the API and are meant for bucket configuration.

aws s3 sync ./site s3://example-site/ --delete --exclude '*.tmp' --dryrun
aws s3 sync ./site s3://example-site/ --delete --exclude '*.tmp'
aws s3api put-bucket-versioning --bucket example-site \
  --versioning-configuration Status=Enabled

Note: in s3 sync the flag is --dryrun, with no hyphen, unlike EC2’s --dry-run. Always run with it before a --delete.

IAM: users, roles, and old keys

aws iam list-users --query 'Users[].[UserName,CreateDate]' --output table
aws iam list-roles --query 'Roles[].RoleName' --output text

# access keys created more than 90 days ago (GNU date; on macOS: date -u -v-90d ...)
CUTOFF=$(date -u -d '90 days ago' +%Y-%m-%dT%H:%M:%SZ)
for u in $(aws iam list-users --query 'Users[].UserName' --output text); do
  aws iam list-access-keys --user-name "$u" \
    --query "AccessKeyMetadata[?CreateDate<='${CUTOFF}'].[UserName,AccessKeyId,Status,CreateDate]" \
    --output text
done

The comparison works because ISO 8601 dates sort as text. For each key found, aws iam get-access-key-last-used --access-key-id ... shows the last use. For a full audit, aws iam generate-credential-report and get-credential-report produce a CSV for the whole account. If a key is unused, deactivate it and then delete it.

Tags

aws ec2 create-tags --resources i-0123456789abcdef0 --tags Key=owner,Value=platform-team
aws resourcegroupstaggingapi get-resources --tag-filters Key=env,Values=prod \
  --query 'ResourceTagMappingList[].ResourceARN' --output text
aws resourcegroupstaggingapi tag-resources \
  --resource-arn-list arn:aws:ec2:sa-east-1:123456789012:instance/i-0123456789abcdef0 \
  --tags env=prod,owner=platform-team

The Resource Groups Tagging API sees many services at once and is the foundation for finding zombie resources.

Costs with Cost Explorer

aws ce get-cost-and-usage \
  --time-period Start=2026-10-01,End=2026-11-01 \
  --granularity MONTHLY --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE \
  --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text

The end date is exclusive. Watch out: the Cost Explorer API is billed per request, so do not put this query in a monitoring loop that runs every minute. For cost strategy, see FinOps to cut AWS costs. This command was checked only against the offline help; the local mock does not implement Cost Explorer.

Live logs

aws logs tail /aws/lambda/orders --follow --since 15m --format short
aws logs tail /aws/lambda/orders --since 1h --filter-pattern ERROR

logs tail is the tail -f of CloudWatch Logs. Great during deployments, for example of a function from the AWS Lambda practical guide.

Auto-prompt and CloudShell

Forgot a parameter name? aws ec2 run-instances --cli-auto-prompt opens an assistant with autocompletion for commands, parameters, and documentation. To keep it on, set cli_auto_prompt = on-partial in the profile or use the AWS_CLI_AUTO_PROMPT variable.

AWS CloudShell is a browser-based terminal with the CLI preinstalled and authenticated with your console identity. It has 1 GB of persistent $HOME per Region, at no extra cost, and the session times out after 20 to 30 minutes of inactivity. It is a good option for emergencies, when you are away from your own machine.

Script: inventory across every Region

This script lists running instances in every enabled Region of the account. It passed bash -n and shellcheck and ran against the local mock.

#!/usr/bin/env bash
# ec2-inventory.sh: lists running instances in every enabled Region
set -euo pipefail
export AWS_PAGER=""

read -ra regions <<< "$(aws ec2 describe-regions --query 'Regions[].RegionName' --output text)"

printf '%-15s %-20s %-12s %s\n' REGION INSTANCE TYPE NAME
for r in "${regions[@]}"; do
  # shellcheck disable=SC2016  # the backticks are JMESPath literals, not shell expansion
  aws ec2 describe-instances --region "$r" \
    --filters Name=instance-state-name,Values=running \
    --query 'Reservations[].Instances[].[InstanceId,InstanceType,Tags[?Key==`Name`]|[0].Value || `"-"`]' \
    --output text |
  while IFS=$'\t' read -r id type name; do
    printf '%-15s %-20s %-12s %s\n' "$r" "$id" "$type" "$name"
  done
done

Run it with AWS_PROFILE=dev ./ec2-inventory.sh. Without --all-regions, describe-regions returns only the enabled Regions. To review set -euo pipefail and loops, see what a shell and shell scripting are.

Safety: dry-run, least privilege, and MFA

  • Test first: --dry-run on EC2, --dryrun on s3 sync, and aws sts get-caller-identity before anything in production.
  • Least privilege: your everyday profile should be read-only or PowerUser. Administrator privilege lives in a separate role, assumed only when needed and with a short session (duration_seconds).
  • MFA: require MFA in IAM Identity Center or at console sign-in. If an IAM user with a key still exists, an assume role profile can prompt for the code with mfa_serial.
  • No keys in code: in CI, use OIDC with a role; on EC2, ECS, and Lambda, use the service role.

Checklist

  • AWS CLI v2 installed with the signed script and aws --version checked
  • No IAM user access keys for human use; aws login or IAM Identity Center instead
  • ~/.aws/config with separate profiles and an administrator role through role_arn and source_profile
  • aws sts get-caller-identity before any command in production
  • --query with --filters, and --output table or text depending on the use
  • --dry-run, --dryrun, and waiters in every script that changes state
  • Periodic scan for access keys older than 90 days

The best AWS CLI credential is the one that expires on its own: let sign-in and roles do the work for you.

Get updates on new posts and stay in the loop!