Quantcast
Channel: Lambda – Radish Logic
Viewing all articles
Browse latest Browse all 3

How to get the AWS Account ID in Lambda Python

$
0
0

There are use cases where the need to get the AWS Account ID of the Lambda Function during runtime is required. I thought it was easy as getting the AWS Region but it was not. Luckily there is a way to get it, use the step-by-step instructions below.

To get the AWS Account ID where the Lambda Function is running use the code below.

def lambda_handler(event, context):

    aws_account_id = context.invoked_function_arn.split(":")[4]

    print(aws_account_id)

How does the code work?

The context object that is being passed to the lambda_handler function provides different methods and properties about the lambda function, like invocation and execution environment.

One of those information is the ARN of the current Lambda Function.

To get the ARN of the Lambda Function use context.invoked_function_arn.

lambda_function_arn = context.invoked_function_arn
print(lambda_function_arn)

Output

arn:aws:lambda:us-east-1:123456789012:function:LambdaFunctionName

The 12 digit 123456789012 is the AWS Account ID.

If we split the ARN by the character colon (:), the fifth element would be the AWS Account ID.

lambda_function_arn = context.invoked_function_arn
aws_account_id = lambda_function_arn.split(":")[4]
print(aws_account_id)

To get the AWS Account ID in one line, we replace lambda_function_arn in line 2 with context.invoked_function_arn.

aws_account_id = context.invoked_function_arn.split(":")[4]
print(aws_account_id)

Output

123456789012

Viewing the Raw Output of context

I was curious what the output of context really is, so I decided to dig deeper about it.

Here is the documentation from AWS: https://docs.aws.amazon.com/lambda/latest/dg/python-context.html

Then checked all the variables of context.

print(vars(context))

Output

{
  'aws_request_id': '425b753c-27c0-4abd-85f4-75f6b8e1ae9e', 
  'log_group_name': '/aws/lambda/LambdaFunctionName', 
  'log_stream_name': '2020/04/04/[$LATEST]eee138c1adb3499fbfcdb69f16fcf2c2', 
  'function_name': 'LambdaFunctionName', 
  'memory_limit_in_mb': '128', 
  'function_version': '$LATEST', 
  'invoked_function_arn': 'arn:aws:lambda:us-east-1:123456789012:function:LambdaFunctionName', 
  'client_context': None, 
  'identity': <bootstrap.CognitoIdentity object at 0x7f37294665b0>, 
  '_epoch_deadline_time_in_ms': 1586007824464
}

Depending on your use case, a lot of information can be used in the context object.

I hope the above helped on gettting the AWS Account ID during Lambda Function runtime.

If there you have questions or any errors that you encountered let me know on the comments below.

The post How to get the AWS Account ID in Lambda Python appeared first on Radish Logic.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images