How can I get list of all Instances running under multiple Accounts by using Aws CLI
I have my profile configured, need assistance with looping, assume roles and than write output in a file
Cheers
How can I get list of all Instances running under multiple Accounts by using Aws CLI
I have my profile configured, need assistance with looping, assume roles and than write output in a file
Cheers
I assume you've already configured one AWS profile for each AWS account and those AWS profiles permit to assume a role having the ec2:DescribeInstances action (this is typically configured inside the ~/.aws/credentials and ~/.aws/config files).
The following script (list-instances.sh) could be written.
Default AWS region version
#!/bin/bash AWS_PROFILES=() AWS_PROFILES[0]=profile_for_account_1 AWS_PROFILES[1]=profile_for_account_2 AWS_PROFILES[2]=profile_for_account_3 for AWS_PROFILE in ${AWS_PROFILES[*]} do echo "== Profile '${AWS_PROFILE}' ==" aws ec2 describe-instances --profile "${AWS_PROFILE}" --filters Name=instance-state-code,Values=16 | jq -r '.Reservations[].Instances[].InstanceId' done Multi-regions version
#!/bin/bash AWS_PROFILES=() AWS_PROFILES[0]=profile_for_account_1 AWS_PROFILES[1]=profile_for_account_2 AWS_PROFILES[2]=profile_for_account_3 for AWS_PROFILE in ${AWS_PROFILES[*]} do for AWS_REGION in $(aws ec2 describe-regions | jq -r '.Regions[].RegionName') do echo "== profile: ${AWS_PROFILE}, region: ${AWS_REGION}" aws ec2 describe-instances --profile "${AWS_PROFILE}" --region "${AWS_REGION}" --filters Name=instance-state-code,Values=16 | jq -r '.Reservations[].Instances[].InstanceId' done done jq command to parse the JSON output (see https://stedolan.github.io/jq/) ; --filters returns only EC2 instances in the running, be careful because it will not list instances in pending, shutting-down or stopping states (see the instance-state-code filter documentation here https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) ;./list-instances.sh > instance-identifiers.txt. Then simply use cat instance-identifiers.txt | grep -v "==" | cat to loop again (here the cat command apply on each EC2 instance identifier, you can replace it by another command).Hope this helps.
Baptiste