Way to run aws cli across multiple accounts

时光怂恿深爱的人放手 提交于 2021-01-28 07:13:35

问题


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?


回答1:


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.




回答2:


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:

  • Deprecated AMIs might not have accessible information, so might be marked a non-Amazon.
  • This script, as written, only works on one region. You could change it to loop through regions.
  • This script, as written, only works on one account. You would need a way to loop through credentials for other accounts.


来源:https://stackoverflow.com/questions/57359926/way-to-run-aws-cli-across-multiple-accounts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!