AWS Lambda Lookup AccountId and Region
For a number of uses including generating IAM roles and various policies, lambda code might require access to current account id and region. Here is a code snippet on how to acquire those values:
import json
import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info(json.dumps(event))
account_id = boto3.client('sts').get_caller_identity().get('Account')
# use a client which is region based
logs_client = boto3.client('logs')
region_name = logs_client.meta.region_name
logger.info(f"{account_id}:{region_name}")