If you want to get the AWS Account ID of your Lambda Function while it is running then you can use the code below. The code below is written in Ruby.
def lambda_handler(event:, context:)
aws_account_id = context.invoked_function_arn.split(":")[4]
puts aws_account_id
end
The AWS Account ID will be stored in the variable aws_account_id
, which you can use for further processing.
How does the code work?
The context
object that is being passed as a parameter to the lambda_handler
has a lot of information in it. One of that information is the invoked_function_arn
.
The invoked_function_arn
is the unique identifier of the running Lambda Function, which contains the AWS Account ID.
def lambda_handler(event:, context:)
lambda_function_arn = context.invoked_function_arn
puts lambda_function_arn
end
Output
arn:aws:lambda:us-east-1:0123456789012:function:GetAccountIdRuby
To get the AWS Account ID, we will need to split the Lambda Function ARN with the colon character (:). Then the fifth item will be the AWS Account ID.
Note: The fifth item is on index 4.
def lambda_handler(event:, context:)
lambda_function_arn = context.invoked_function_arn
aws_account_id = lambda_function_arn.split(":")[4]
puts aws_account_id
end
Output is the AWS Account ID.
0123456789012
To make the code shorter, we can combine getting the Lambda Function ARN, splitting, and getting the fifth item into one line.
def lambda_handler(event:, context:)
aws_account_id = context.invoked_function_arn.split(":")[4]
puts aws_account_id
end
Output is still the AWS Account ID.
0123456789012
Showing the contents of context
object
The context parameter has a lot of information contained inside. Below is a code in Ruby where you can check the contents of the context
object being passed to the Lambda Function.
def lambda_handler(event:, context:)
puts context.inspect
end
The output below is formatted to different lines per item for easier reading.
#<LambdaContext:0x0000000002b78f48
@clock_diff=1641910854004,
@deadline_ms=1641911732244,
@aws_request_id="e3f31d5e-1b8b-6f89-9118-0bd5caf9b6ae",
@invoked_function_arn="arn:aws:lambda:us-east-1:123456789012:function:GetAccountIdRuby",
@log_group_name="/aws/lambda/GetAccountIdRuby",
@log_stream_name="2022/01/11/[$LATEST]1d7dbce6199249bdbad2d616bac0c4a6",
@function_name="GetAccountIdRuby",
@memory_limit_in_mb="128",
@function_version="$LATEST"
>
Reading the AWS Documentation on the Ruby context object of the AWS Lambda Function shows that there are more data it can contain than the one above.
Since we have already retrieved the AWS Account ID of our running Lambda Function using Ruby, we’ll end this post. I hope this helps.