amazon-web-servicesamazon-ec2aws-cli

How to list all EC2 instances of multiple accounts (profiles)


Is there an option I can give this command to make it iterate through all my profiles/accounts?

aws ec2 describe-instances --query "Reservations[*].Instances[*].
{PublicIP:PublicIpAddress,Type:InstanceType,Name:Tags[?Key=='Name']|
[0].Value,Status:State.Name}"  --filters "Name=instance-state-name,Values=running"
"Name=tag:Name,Values='*'"  --output table

I have to run this in multiple accounts and I was wondering if there's a way to avoid writing a script that loop through all the profiles

I can't find anywhere if there is something like --profile allProfiles or --profiles [*]


Solution

  • You will need to create a simple script since aws cli only works for a single profile.

    In bash, that would be something like:

    for profile in `aws configure list-profiles`; do aws ec2 describe-instances --profile $profile ;done;   
    

    What might be useful is to append each command's output to the same file and then process the file as if it was the output of a single command:

    outputFile=`mktemp` ; for profile in `aws configure list-profiles`; do aws ec2 describe-instances --profile  $profile >> $outputFile  ;done; cat $outputFile
    

    For json you might want to process the commands output via jq before appending to file.