Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get accountId where Lambda deployed to programmatically?

I would like get accountId of AWS account where Lambda is deployed to.

Will boto3.client('sts').get_caller_identity()['Account'] return lambda's account of deployment itself, or account of lambda caller?

What is the correct way of getting Lambda AWS accountId inside its own code?

like image 325
Rudziankoŭ Avatar asked May 11 '26 10:05

Rudziankoŭ


1 Answers

Lambda runs are invoked with a set of environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, AWS_SESSION_TOKEN, etc, which are the same as would result from a direct call to sts.assume_role() assuming the role specified in the configuration of the lambda function. If you look at the full output of get_caller_identity() you see the Arn field is the normal arn-of-role-slash-name-of-entity-assuming-the-role. So I presume that the value of the Account field is technically the account owning the IAM Role that's being assumed, but since (AFAIK?) that has to be from the same account as the lambda function itself, I think that's a reliable indicator of the account of the lambda function.

Personally, I set an AWS_ACCOUNT_ID environment variable on most/all of my lambda functions, which is really easy to pass through in CloudFormation as AWS_ACCOUNT_ID: { Ref: "AWS::AccountId" }.

like image 76
Stephen Avatar answered May 13 '26 00:05

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!