12

I have access to

com.amazonaws.services.lambda.runtime.Context;

object and by extension the invoked function Arn. The arn contains the account Id where the lambda resides.

My question is simple, I want the cleanest way to extract the account Id from that.

I was taking a look

com.amazon.arn.ARN;

It has a whole bunch of stuff, but no account ID (which i presume is due to the fact that not all arns have account ids ?)

I want to cleanly extract the account Id, without resorting to parsing the string.

5 Answers 5

23

If your lambda is being used as an API Gateway proxy lambda, then you have access to event.requestContext.accountId (where event is the first parameter to your handler function).

Otherwise, you will have to split the ARN up.

From the AWS documentation about ARN formats, here are the valid Lambda ARN formats:

arn:aws:lambda:region:account-id:function:function-name

arn:aws:lambda:region:account-id:function:function-name:alias-name

arn:aws:lambda:region:account-id:function:function-name:version

arn:aws:lambda:region:account-id:event-source-mappings:event-source-mapping-id

In all cases, account-id is the 5th item in the ARN (treating : as a separator). Therefore, you can just do this:

String accountId = arn.split(":")[4];
2
  • 2
    Sigh, that is what i was hoping to avoid. Mar 8, 2018 at 1:25
  • 4
    Yes, it's a little nasty. At least the various ARN formats are easily accessible on the docs site. Mar 8, 2018 at 3:10
8

You no longer need to parse the arn anymore, sts library has introduced get_caller_identity for this purpose. Its an overkill, but works!.

Excerpts from aws docs.

python

import boto3

client = boto3.client('sts')
response = client.get_caller_identity()['Account']

js

/* This example shows a request and response made with the credentials for a user named Alice in the AWS account 123456789012. */

 var params = {
 };
 sts.getCallerIdentity(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
   /*
   data = {
    Account: "123456789012", 
    Arn: "arn:aws:iam::123456789012:user/Alice", 
    UserId: "AKIAI44QH8DHBEXAMPLE"
   }
   */
 });

More details here & here

6
  • For Python3, in my Lambda function, this worked: account = client.get_caller_identity().get('Account') Oct 7, 2020 at 14:45
  • there is an erroneous extra brace at the end of your python example: response = client.get_caller_identity()['Account']) should be response = client.get_caller_identity()['Account'] Oct 8, 2020 at 14:59
  • Corrected! Thanks. Oct 8, 2020 at 15:01
  • 1
    you need to have the sts:GetCallerIdentity IAM permission for this to work Dec 11, 2020 at 20:57
  • 2
    Note that this gets the caller's account id. This might be different than the account id of the account that is hosting the lambda. If you gave given permission to another account to call your lambda, you will get the caller's account id, not your account id Jan 19, 2021 at 19:13
1

I use this:

ACCID:  { "Fn::Join" : ["", [{ "Ref" : "AWS::AccountId" }, "" ]] }
2
  • yea i know how to ref it in CFN. I wanted a lambda only method (so as to be agnostic to how the lambda was created). Apr 2, 2018 at 23:20
  • This gives a dummy account id when doing a SAM local invoke using a AWS profile so ends up being problematic for my use case.
    – ppearcy
    Aug 4, 2020 at 18:33
1

golang

import (
    "github.com/aws/aws-lambda-go/lambdacontext"
)

func Handler(ctx context.Context) error {
    lc, ok := lambdacontext.FromContext(ctx)
    if !ok {
        return errors.Errorf("could not get lambda context")
    }
    AwsAccountId := strings.Split(lc.InvokedFunctionArn, ":")[4]
0

I would get the Account id from the context parameter in the following way.

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

aws doc referring context parameter - https://docs.aws.amazon.com/lambda/latest/dg/python-context.html

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.