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?
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" }.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With