AWS cli is a very powerful command line utility provided by AWS.
Here I am giving a set of AWS CLI commands to list the EC2 instances in an aws account.
List all EC2 instances in an AWS account (including stopped).
aws ec2 describe-instance-status --include-all-instances
The above command will list all the EC2 instances in an account irrespective of its status. The output will be in JSON format.
List all EC2 instances in an AWS account of a specific state (running or stopped) in a tabular format
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[*].{InstanceType: InstanceType, InstanceId: InstanceId, State: State.Name}' --output table
The above command will list all the EC2 instances which is in running state in a tabular format. You can query any state by adjusting the filter condition in the command.
List the EC2 instances and a value of a specific tag (in this example, the value of the Name tag)
aws ec2 describe-instances --query 'Reservations[].Instances[].{Name: Tags[?Key==Name
].Value | [0]}' --output text
The above command will list the EC2 instances with the tag Name. You can adjust this query based on your need.
List the EC2 instances by filtering it with a specific tag
aws ec2 describe-instances --filter "Name=tag:Name,Values=*"
The above command will list the EC2 instances which satisfies the filter condition. In the above example I have used * as the Value. So it will print everything which has a Name tag. But if you want to filter the instances with a specific tag value, you can use that in the condition instead of the *. An example is given below. This will list the instances which has the Name tag value Amal
aws ec2 describe-instances --filter "Name=tag:Name,Values=Amal"
I hope these commands are useful. Feel free to comment if you have any queries or feedback.