1

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)
Marcin
  • 215,873
  • 14
  • 235
  • 294
Flo Flo
  • 29
  • 3
  • Does this answer your question? [AWS: Boto3: AssumeRole example which includes role usage](https://stackoverflow.com/questions/44171849/aws-boto3-assumerole-example-which-includes-role-usage) – luk2302 Oct 07 '21 at 07:12
  • You need to assume a role in the target account prior to running the actual ec2 commands. – luk2302 Oct 07 '21 at 07:12

1 Answers1

0

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.

Marcin
  • 215,873
  • 14
  • 235
  • 294
  • Thank you for the input. Would it be easier and better to just create a user and access keys in my account, instead of always generating temporary credentials? Sorry if it's a stupid question, but i'm not experienced in AWS – Flo Flo Oct 07 '21 at 11:33
  • Hello Marcin, i have one more question. I want to access from my python lambda function using boto3 more then one resource type. I need to access EC2 to describe instance, SQS to check queue attribute, and to send data to an SNS Topic. Do i need to get the temporary credentials for every aws recource? Or are the credentials available for the whole boto3 session? – Flo Flo Oct 08 '21 at 06:55
  • Im reffering to this part of code `# Use the temporary credentials that AssumeRole returns to make a connection to Amazon EC2 ec2_resource = boto3.resource('ec2', aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], )` – Flo Flo Oct 08 '21 at 06:56