Search code examples
amazon-web-servicesaws-lambdaamazon-iamaws-organizations

Retrieve Role ARNs of sub accounts from an AWS lambda function running in the master account, in AWS organizations


I have a lambda function which assumes roles of sub accounts in AWS organizations. The lambda resides in the master account. I need to pass the Role ARN of the role to be assumed to this lambda. How can I achieve this? How can I retrieve role ARNs of roles residing in sub accounts from the master account using AWS Lambda ?


Solution

  • Is the role name different in every account? If the name of the role is the same, you can use essentially the same ARN and just insert the account ID into the string for whichever account is calling the Lambda function. I'm not sure if this answers your question, but if this is what you're trying to do your Lambda function code might look something like this (using Python and boto3):

    def lambda_handler(event, context):
        roleARN = 'arn:aws:iam::'+event['accountId']+':role/your_role_name'
    
        sts_connection = boto3.client('sts')
        # Assume the role in member accounts
        acct_b = sts_connection.assume_role(
            RoleArn=roleARN,
            RoleSessionName="session_name"
        )
    

    Keep in mind that you will need to have the permissions set up correctly for both roles. The Lambda execution role needs to have permission to assume a role with that common name in any account, and the member account roles need to allow your Lambda execution role to assume them in the trust policy.