How to Get Account Number from AWS Lambda
If you need to get the current Account Number, or Account ID from within a Lambda execution, then you can access invoked_function_arn from the context and return the associated value as follows:
aws_account_id = context.invoked_function_arn.split(":")[4]
This is useful when your Lambda needs to construct ARNs dynamically or make cross-account API calls. I use this pattern in multi-account setups where the same Lambda code deploys to different AWS accounts and needs to know which one it’s running in.
The ARN format is arn:aws:lambda:region:account-id:function:name, so splitting on : and grabbing index 4 gives you the account ID. An alternative is calling sts.get_caller_identity(), but that adds an API call and latency. The context approach is instant since the data is already available in the Lambda runtime.