Cheat sheet de AWS CLI

Referencia de AWS CLI con búsqueda: configuración, S3, EC2, VPC/Route 53, CloudWatch, Lambda, ECR/ECS, IAM y CloudFormation, con cada opción explicada.

Se ejecuta en tu navegador · no se envía nadaNuevo

48 comandos

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.

Opciones

--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.

Ejemplo

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.

Ejemplo

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

Opciones

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.

Ejemplo

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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

--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).
Cuidado: --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.

Ejemplo

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

Opciones

--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.
Cuidado: 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.

Ejemplo

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

Opciones

--forceOn rb (remove bucket): delete all objects in the bucket first, then the bucket itself.
Cuidado: "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.

Ejemplo

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

Opciones

--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).

Ejemplo

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

Opciones

--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.

Opciones

--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.
Cuidado: 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.
Cuidado: 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.

Ejemplo

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

Opciones

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

Abrir Analizador de Security Groups de AWS →

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.

Cuidado: 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.

Ejemplo

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>".

Abrir Analizador de políticas IAM →

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.

Ejemplo

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/*

Opciones

--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.
Cuidado: 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.

Ejemplo

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

Opciones

--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.
Cuidado: 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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

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

Abrir Planificador de VPC/subred →

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.

Ejemplo

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.

Ejemplo

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.

Ejemplo

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.

Cuidado: 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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

--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.

Ejemplo

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

Opciones

--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.

Ejemplo

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.

Opciones

--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.
Cuidado: 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.

Ejemplo

aws lambda update-function-configuration --function-name my-function --environment "Variables={STAGE=prod}"
Cuidado: --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.

Ejemplo

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.

Opciones

--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.

Las descripciones de esta referencia están por ahora en inglés.

Explicación

Busca o filtra por grupo y copia un comando con un clic. Abre un comando para ver qué hace, un ejemplo y cada opción que acepta, con avisos para todo lo que elimine o termine un recurso.

🔒 Tu entrada se queda en tu navegador y no se envía a ningún sitio.

Preguntas frecuentes

¿Cuál es la diferencia entre --query y --filters?

--filters se envía a AWS y limita qué elementos devuelve la API. --query se ejecuta después de recibir la respuesta y la reestructura en el cliente con una expresión JMESPath. Se pueden combinar.

¿Cómo sigo los logs de Lambda desde la CLI?

aws logs tail /aws/lambda/<nombre-de-función> --follow transmite nuevas entradas de log a medida que llegan, similar a tail -f. Añade --since 1h para ver también el historial reciente primero.

Qué hacer después

Más en esta sección

  • Cheat sheet de Azure CLIReferencia de comandos de Azure CLI con búsqueda: inicio de sesión, grupos de recursos, VMs, almacenamiento, web apps y AKS, con cada parámetro explicado.
  • Cheat sheet de AnsibleReferencia de comandos de Ansible con búsqueda: comandos ad-hoc, playbooks, roles, plantillas, handlers, bucles, Vault y Galaxy, con cada parámetro explicado.

También útil

  • Analizador de Security Groups de AWSPega una exportación de describe-security-groups para encontrar puertos abiertos, reglas redundantes u ocultas, un diagrama y el impacto de eliminarlas.
  • Analizador de políticas IAMPega una política IAM de AWS para detectar permisos demasiado amplios, rutas de escalada de privilegios y riesgos de confused deputy, y simula solicitudes.
  • Planificador de VPC/subredPlanifica subredes dentro de una VPC o VNet, ve las direcciones utilizables tras las reservas del proveedor, detecta solapamientos y exporta Terraform o CloudFormation.
  • Generador de scripts de auditoríaScripts y consultas listas para usar, de solo lectura, para auditorías de SQL, Active Directory, AWS CLI y Azure CLI. Marca y copia el script combinado.

¿Has encontrado un problema o tienes una sugerencia? Cuéntanoslo