Pulling AWS accountID from CloudTrail to use in Lambda function

358 views Asked by At

I'm working to pull the accountID from a newly created AWS account within an organization. I'm using a CloudWatch rule that triggers the lambda function off of the CreateAccountResult event name. Within this event, it gives me the createAccountStatus of "SUCCEEDED" as well as the accountID of the new account.

I want to be able to pull JUST the accountID and insert it into a variable within my lambda function.

This lambda function is being used to create an AWS connector to link the account to Trend Micro. Essentially, what I'm using in this script is:

account = '**accountID**'

payload = "{\n   \"crossAccountRoleArn\": \"arn:aws:iam" + account + ":role/TrendMicroDSM\",\n   \"workspacesEnabled\": true\n}"

I want the account variable to automatically update with the newest account's accountID

Is this even possible?

1

There are 1 answers

6
John Rotenstein On

If you are using Python, the create_account() function returns:

{
    'CreateAccountStatus': {
        'Id': 'string',
        'AccountName': 'string',
        'State': 'IN_PROGRESS'|'SUCCEEDED'|'FAILED',
        'RequestedTimestamp': datetime(2015, 1, 1),
        'CompletedTimestamp': datetime(2015, 1, 1),
        'AccountId': 'string',
        'GovCloudAccountId': 'string',
        'FailureReason': 'ACCOUNT_LIMIT_EXCEEDED'|'EMAIL_ALREADY_EXISTS'|'INVALID_ADDRESS'|'INVALID_EMAIL'|'CONCURRENT_ACCOUNT_MODIFICATION'|'INTERNAL_FAILURE'|'GOVCLOUD_ACCOUNT_ALREADY_EXISTS'
    }
}

Therefore, you could simply use:

import boto3

client = boto3.client('organizations')

response = client.create_account(...)

account_id = response['CreateAccountStatus']['AccountId']