To get the AWS Account ID of the currently running Lambda Function using Node.js use the code below.
exports.handler = async (event, context) => {
const awsAccountId = context.invokedFunctionArn.split(':')[4]
console.log(awsAccountId)
};
How does the code work?
Originally, I thought that getting the AWS Account ID of the currently running Lambda Function was easy, since when I tried getting the runtime region I just took it from an environment variable.
Getting the AWS Account ID is a different story because no environment variable represents this.
To get the AWS Account ID of a running Lambda Function, we need to get the Lambda Function’s ARN first. This can be seen inside the context
object.
const lambdaFunctionArn = context.invokedFunctionArn
console.log(lambdaFunctionArn)
Output
arn:aws:lambda:ap-south-1:123456789012:function:GetLambdaAccountID
The 12 digit 123456789012
is the AWS Account ID.
If we split the Lambda Function ARN by the character colon (:), the fifth string would be the AWS Account ID.
const lambdaFunctionArn = context.invokedFunctionArn
const awsAccountId = lambdaFunctionArn.split(':')[4]
console.log(awsAccountId)
We can simplify the code into one line.
const awsAccountId = context.invokedFunctionArn.split(':')[4]
console.log(awsAccountId)
Output
123456789012
The context
object
I was curious what the context object is while writing this post.
I’m not going to explain what it is in this post, but if you want to read more about it I suggest heading to the AWS documentation here.
What I am curious about is what objects are inside it. So here’s how I showed it in the Lambda execution results.
exports.handler = async (event, context) => {
console.log(context)
}
Output
{
callbackWaitsForEmptyEventLoop: [Getter/Setter],
succeed: [Function (anonymous)],
fail: [Function (anonymous)],
done: [Function (anonymous)],
functionVersion: '$LATEST',
functionName: 'GetLambdaAccountID',
memoryLimitInMB: '128',
logGroupName: '/aws/lambda/GetLambdaAccountID',
logStreamName: '2021/07/08/[$LATEST]b4db7434ee6a4d76bc44285d3b61eba4',
clientContext: undefined,
identity: undefined,
invokedFunctionArn: 'arn:aws:lambda:ap-south-1:123456789012:function:GetLambdaAccountID',
awsRequestId: '0e642f8c-bebb-4153-9763-d9fdaa42b44f',
getRemainingTimeInMillis: [Function: getRemainingTimeInMillis]
}
We hope this helps you get the AWS Account ID of the running AWS Lambda Function using Node.js.