Home > Software engineering >  Count the number of EC2 instances cross-account
Count the number of EC2 instances cross-account

Time:10-08

I need to create a python lambda function which check a set of conditions. One of the is to count the number of running ec2 instances with a specific name from another aws account.

I searched stackoverflow and found something like this, but this should only count the instances from the same account/region.

def ec2(event, context):
ec2_resource = boto3.resource('ec2')
instances = [instance.state['Name'] for instance in ec2_resource.instances.all()]
ec2_running_instances = instances.count('running')
print(ec2_running_instances)

CodePudding user response:

You can't do this directly from your account. You must assume IAM role that is created in the second account, with permissions to describe the instances. Please check: Delegate access across AWS accounts using IAM roles .

Once the role exists, you have to use boto3's assume_role to assume the role, get temporary aws credentials, and then create new boto3 session with that credentials.

  • Related