AWS CLI Script to list all the EC2 Servers in all AWS Accounts in all Regions

 To list all EC2 servers across all AWS accounts and regions using AWS CLI, you can use the aws command with the ec2 describe-instances option and specify the --profile and --region options for each account and region.

Here's an example command that you can use as a starting point:


#!/bin/bash # List of AWS accounts and regions accounts=("account1" "account2") regions=("us-east-1" "us-west-2" "eu-west-1") # Loop through the accounts and regions for account in "${accounts[@]}" do for region in "${regions[@]}" do # Set the profile and region export AWS_PROFILE=$account export AWS_DEFAULT_REGION=$region # Get the EC2 instances in the region instances=$(aws ec2 describe-instances --query 'Reservations[].Instances[].InstanceId' --output text) # Print the instances echo "Instances in $account - $region:" echo "$instances" done done

In this script, you define an array accounts with the names of the AWS accounts you want to list EC2 instances for, and an array regions with the names of the AWS regions you want to list EC2 instances in.

The script then loops through the accounts and regions using nested loops. For each account and region, it sets the AWS_PROFILE and AWS_DEFAULT_REGION environment variables to the current account and region, and uses the aws ec2 describe-instances command to get a list of EC2 instances in that region. The --query option is used to extract only the instance IDs from the output, and the --output option is set to text to make the output easier to parse.

The script then prints the list of instances for each account and region.

Note that you will need to have the necessary permissions and credentials set up for each AWS account in order for this script to work.

Comments

Popular posts from this blog

Linux : Special permissions to users for file & directories using "setfacl"

Linux : Port Numbers for common services