Rudziankoŭ
Rudziankoŭ

Reputation: 11251

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?

Upvotes: 8

Views: 9754

Answers (2)

Martin Forte
Martin Forte

Reputation: 873

You can easily get it from the context:

def lambda_handler(event, context):
    aws_account_id = context.invoked_function_arn.split(":")[4]
    print(aws_account_id)

If you are interested in how it works you can read this

Upvotes: 5

Stephen
Stephen

Reputation: 1805

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" }.

Upvotes: 16

Related Questions