AWS CloudShell: 10 practical commands to explore your environment

AWS CloudShell: 10 practical commands to explore your environment

Learn how to use AWS CloudShell to inventory resources, investigate events, and review security, monitoring, and storage information. Practice with a temporary lab and follow the cleanup steps when you’re done.

Entrepreneur & AWS Instructor at VocêCertificado®
AWS CloudShell is a browser-based terminal accessible directly from the AWS Management Console. Its main advantage is that the AWS Command Line Interface (AWS CLI) is already installed and uses your session credentials, allowing you to run commands without installing tools or configuring access keys on your computer.
In this article, we’ll learn how to use AWS CloudShell to generate an instance inventory, find unattached resources, investigate events, and retrieve security, monitoring, and storage information.
To help you practice the ten examples, I’ve provided an AWS CloudFormation template that sets up a temporary, controlled environment.
Watch out for costs!
AWS CloudShell is available at no additional charge. However, the resources created in this lab and requests to the services you query, such as listing objects in Amazon S3, may incur charges. In my controlled tests, the lab cost a few US cents. The amount may vary depending on how long the resources remain provisioned, the number of requests, and pricing in the selected Region. When you finish, confirm that the environment has been deleted.




Video Tutorial

This video includes English and Spanish audio tracks. Select your preferred language in the YouTube player settings.





Lab Setup

You’ll need an AWS account, access to CloudShell, and an identity with the  AdministratorAccess  policy.
In CloudShell, we’ll use Bash, along with the AWS CLI and  jq , a tool for processing JSON responses. Both are available in the default environment.
  1. Open the  lab-cloudshell.yaml file on GitHub  and select Download raw file to download it.
  1. In the AWS console, select US East (N. Virginia),  us-east-1 .
  1. Open AWS CloudFormation, choose Create stack, and select the option to upload a template file.
  1. Upload the YAML file and, in the next step, enter  cloudshell  as the stack name.
  1. Keep the default parameters. In the configuration step, select the acknowledgment that CloudFormation may create IAM resources with custom names.
  1. Review the settings and submit the request.
  1. Wait for the  CREATE_COMPLETE  status. Then open CloudShell in the same Region to run the examples.



The template sets up an EC2 instance, EBS volumes, an unassociated Elastic IP address, Lambda functions, a CloudWatch alarm, and the resources needed for automation. It does not create buckets or files in Amazon S3.
The EC2 instance is stopped automatically during setup. The template also schedules a stack deletion request for ten minutes after the instance is stopped. Check the time under Outputs →  DeletionTimeUtc , displayed in UTC. The schedule has one-minute precision, and deletion takes additional time.
Don’t rely solely on this automation!
If stack creation fails before the schedule is configured, automatic deletion will not be set up. When you finish, check the stack status and clean up as described after Example 10.
Regional queries may show other resources in your account in addition to those created by the lab. Empty results may indicate that no resources match the query, while  AccessDenied  errors indicate insufficient permissions.




1. Export an EC2 Inventory to CSV

The first command lists the ID, type, state, and private IP address of  Amazon EC2  instances in the current Region.  jq formats the response and adds a header to the  inventario-ec2.csv  file.

aws ec2 describe-instances --output json |
jq -r '
["ID","Tipo","Estado","IP privado"],
(.Reservations[].Instances[] |
[.InstanceId,.InstanceType,.State.Name,.PrivateIpAddress])
| @csv
' > inventario-ec2.csv

The file will be saved in the current directory. If another file with the same name already exists, it will be overwritten.
To view its contents in the terminal, run:
cat inventario-ec2.csv




2. Find Unattached EBS Volumes

In addition to checking instances, we can identify Amazon EBS volumes that are unattached.
The following command filters volumes in the  available  state and displays their ID, size in GiB, and type.
aws ec2 describe-volumes \
--filters Name=status,Values=available \
--query 'Volumes[].{ID:VolumeId,TamanhoGiB:Size,Tipo:VolumeType}' \
--output table
The additional 1 GiB volume created by the lab should appear in the results.


Example of an EBS volume query using AWS CloudShell




3. Investigate Requests to Stop EC2 Instances

To investigate requests to stop instances, we can query AWS CloudTrail.
This command displays the ten most recent  StopInstances  events available in the Region’s event history, including the date, identity, and associated resources. The history covers the past 90 days.
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=StopInstances \
--max-items 10 \
--query 'Events[].{Quando:EventTime,Identidade:Username,Recursos:Resources}' \
--output json
In this lab, the stop request is made by the  cloudshell-lab  Lambda function.
The event may take a few minutes to appear and remains in the history after the stack is deleted.


Example of an EC2 event query using AWS CloudShell




4. Locate Inbound Rules Open to Any IP Address

We can also query security group inbound rules.
The following example finds rules with an IPv4 source of  0.0.0.0/0  or an IPv6 source of  ::/0 , displaying the group, protocol, and port range.
aws ec2 describe-security-group-rules \
--query 'SecurityGroupRules[?IsEgress==`false` && (CidrIpv4==`0.0.0.0/0` || CidrIpv6==`::/0`)].{Grupo:GroupId,Protocolo:IpProtocol,De:FromPort,Ate:ToPort,IPv4:CidrIpv4,IPv6:CidrIpv6}' \
--output table
The lab’s TCP/80 rule should appear. However, an open rule alone does not prove that a resource is accessible from the internet. You also need to consider routes, addresses, and other network controls.
In this environment, the rule is for demonstration purposes. The instance does not receive a public IP address, and the VPC has neither an internet gateway nor a NAT gateway.






5. Find Unassociated Elastic IP Addresses

Another useful query identifies unassociated Elastic IP addresses in the current Region. These addresses remain allocated to the account and incur charges until they are released.
aws ec2 describe-addresses \
--query 'Addresses[?AssociationId==`null`].{IP:PublicIp,Alocacao:AllocationId}' \
--output table
The Elastic IP address created by the lab remains unassociated so that it appears in these results.


Example of an Elastic IP address query using AWS CloudShell




6. Identify Metric Alarms in the ALARM State

To check the environment’s monitoring, this command lists Amazon CloudWatch metric alarms in the  ALARM  state, along with the reason reported by the service.
aws cloudwatch describe-alarms \
--state-value ALARM \
--query 'MetricAlarms[].{Alarme:AlarmName,Motivo:StateReason}' \
--output table
The lab alarm uses  TreatMissingData: breaching , a setting that treats missing data as a threshold breach. As a result, it should enter the  ALARM  state after evaluation without indicating an actual application failure.
This alarm does not send notifications or perform actions on the EC2 instance. The query returns only metric alarms and does not list composite alarms.


Example of an alarm query using AWS CloudShell




7. Query Adjustable Amazon EC2 Quotas

In addition to existing resources, we can query the available limits.
The following command uses Service Quotas to list adjustable Amazon EC2 quotas with values greater than zero.
aws service-quotas list-service-quotas \
--service-code ec2 \
--query 'Quotas[?Adjustable==`true` && Value>`0`].{Cota:QuotaName,Valor:Value,Ajustavel:Adjustable}' \
--output table --no-cli-pager
The values represent limits provided by the service, rather than current resource usage.
This query does not request increases or change the account’s quotas.


Example of a quota query using AWS CloudShell




8. Find the Ten Largest Objects in Each S3 Bucket

For Amazon S3, the following script discovers the account’s general purpose buckets and displays up to ten of the largest objects in each one.
(
set -euo pipefail

buckets=$(
aws s3api list-buckets \
--output json \
--no-cli-pager
)

if [ "$(jq '.Buckets | length' <<< "$buckets")" -eq 0 ]; then
printf 'Nenhum bucket encontrado.\n'
exit 0
fi

while IFS= read -r bucket; do
printf '\nBucket: %s\n' "$bucket"

if objetos=$(
aws s3api list-objects-v2 \
--bucket "$bucket" \
--output json \
--no-cli-pager
); then
jq '
(.Contents // []) |
sort_by(.Size) |
reverse |
.[:10] |
map({
Arquivo: .Key,
TamanhoMiB: ((.Size / 1048576 * 100 | round) / 100)
})
' <<< "$objetos"
else
printf 'Não foi possível consultar este bucket.\n'
fi
done < <(jq -r '.Buckets[].Name' <<< "$buckets")
)
The results display sizes in MiB and consider current objects, excluding previous versions and incomplete multipart uploads. Empty buckets return  [] . If a query fails, the script reports the problem and continues to the next bucket.
Unlike the previous regional queries, this example may query buckets in other Regions, depending on the permissions of the identity being used. It retrieves metadata without downloading files and does not cover directory buckets.
Pay attention to the number of objects!
The script lists all current objects in each bucket before sorting them. For large buckets, this may take time, consume memory in CloudShell, and generate many list requests. Since the template does not create S3 resources, the results depend on the buckets already in your account.


Example of an S3 object listing using AWS CloudShell




9. Check Lambda Function Runtimes

Returning to regional resources, we can list  AWS Lambda  functions to check their names, runtimes, which identify their execution environments, and configured memory.
aws lambda list-functions \
--query 'Functions[].{Funcao:FunctionName,Runtime:Runtime,MemoriaMB:MemorySize}' \
--output table
In the lab, the results will show the demonstration function and the setup function, both using Node.js 22 and 128 MB of memory.
Functions deployed as container images may not have a value in the  Runtime  field.


Example of a Lambda query using AWS CloudShell




10. Check the Status of CloudFormation Stacks

Finally, this command displays the names and statuses of AWS CloudFormation stacks in the current Region.
aws cloudformation describe-stacks \
--query 'Stacks[].{Stack:StackName,Estado:StackStatus}' \
--output table
During testing, the  cloudshell  stack should appear with the  CREATE_COMPLETE  status.
When cleanup begins, it may appear as  DELETE_IN_PROGRESS . Once deletion is complete, it will no longer appear in this query.


Example of a CloudFormation stack query using AWS CloudShell




Lab Cleanup

Do not delete the lab resources individually!
Delete the stack so that CloudFormation can manage resource removal.
After completing the examples, delete the stack through CloudFormation or CloudShell.
In the console, select the  us-east-1  Region, open CloudFormation, select the  cloudshell  stack, and choose Delete. Wait for deletion to finish.
From CloudShell, request deletion with:
aws cloudformation delete-stack \
--stack-name cloudshell \
--region us-east-1
Then wait for completion:
aws cloudformation wait stack-delete-complete \
--stack-name cloudshell \
--region us-east-1
The wait command does not display progress and returns without an error when deletion is complete. If it fails, check the stack events in the console and resolve the cause before considering cleanup complete.
The  cloudshell-exclusao-cfn  IAM role has  DeletionPolicy: Retain , preserving the permissions needed while deletion is in progress. As a result, the role and its inline policy remain after the stack is removed.
Important:
Only after confirming that the stack has been deleted should you run the following block to remove the role:
aws cloudformation wait stack-delete-complete \
--stack-name cloudshell \
--region us-east-1 &&
aws iam delete-role-policy \
--role-name cloudshell-exclusao-cfn \
--policy-name CleanupLab &&
aws iam delete-role \
--role-name cloudshell-exclusao-cfn
These commands assume that the stack was created with the name  cloudshell . Remove the retained role before recreating the lab with the same name to avoid a conflict.




Conclusion

Through these ten examples, we’ve seen how AWS CloudShell can be a practical option for generating reports and inspecting your environment through terminal queries. For specific, occasional requests, it lets you gather useful information without setting up tools on your computer.
Its compute environment is ephemeral, but standard CloudShell provides persistent storage in the $HOME directory. This allows you to preserve files, such as the CSV inventory, between sessions, subject to the service’s retention conditions.
My recommendation is to use these commands as a starting point for queries that make sense for your environment, paying attention to the permissions and scope of each example. The template, commands, and troubleshooting instructions are available in the  AWS CloudShell: 10 Practical Commands repository .
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article