Reputation: 3256
I am trying to find out all EC2 instances in 10 different accounts which are running non-amazon AMI images. Following CLI command gives me the list of all AMI's:
aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].[ImageId]' | sort | uniq -c
I think I can modify this further to get all non-amazon AMI's but is there a way to run this across 10 different accounts in one call?
Upvotes: 2
Views: 2358
Reputation: 1
Old Post, I know, but just ran into this... I use Steampipe (steampipe.org) for these types of queries (with their AWS plugin). We have a dozen or so AWS accounts, so this definitely helps. I use Steampipe daily for my work queries, including other plugins like CVS (awesome plugin) and Crowdstrike.
Steampipe uses SQL and maps these to API calls. You don't need a vast knowledge of SQL to use this, and once your brain gets used to this, it is pretty nice.
SELECT
account_id,
instance_id,
tags->>'Name' AS name_tag
FROM
aws_account_prod.aws_ec2_instance;
WHERE
instance_state = 'running'```
Upvotes: 0
Reputation: 43
Use AWS config
SELECT
accountId,
resourceId,
configuration.keyName,
availabilityZone
WHERE
resourceType = 'AWS::EC2::Instance'
AND configuration.state.name = 'running'
more details https://aws.amazon.com/blogs/mt/org-aggregator-delegated-admin/
Upvotes: 0
Reputation: 269091
Here's a script that can find instances using AMIs where the Owner is not amazon
:
import boto3
ec2_client = boto3.client('ec2', region_name='ap-southeast-2')
instances = ec2_client.describe_instances()
# Get a set of AMIs used on all the instances
images = set(i['ImageId'] for r in instances['Reservations'] for i in r['Instances'])
# Find which of these are owned by Amazon
amis = ec2_client.describe_images(ImageIds=list(images), Owners=['amazon'])
amazon_amis = [i['ImageId'] for i in amis['Images']]
# Which instances are not using Amazon images?
non_amazon_instances = [(i['InstanceId'], i['ImageId']) for r in instances['Reservations'] for i in r['Instances'] if i['ImageId'] not in amazon_amis]
for i in non_amazon_instances:
print(f"{i[0]} uses {i[1]}")
A few things to note:
Upvotes: 0
Reputation: 200446
is there a way to run this across 10 different accounts in one call?
No, that's not possible. You need to write a loop that iterates over each account, calling ec2 describe-instances
once for each account.
Upvotes: 2