AWSTemplateFormatVersion: '2010-09-09' Description: Organization data collections. Parameters: RoleName: Type: String Description: ARN of the IAM role deployed in the management accounts which can retrieve AWS Org data. ECSLambdaARN: Type: String Description: ARN of the lambda function to get data of ecs. CFDataName: Type: String Description: The name of what this cf is doing. Default: 'ecs-services-clusters' Outputs: LambdaFunctionName: Value: Ref: LambdaFunction LambdaFunctionARN: Description: Lambda function ARN. Value: Fn::GetAtt: - LambdaFunction - Arn Resources: LambdaRole: Type: AWS::IAM::Role Properties: RoleName: AWS-Orgonisation-Account-Collector-Role AssumeRolePolicyDocument: Statement: - Action: - sts:AssumeRole Effect: Allow Principal: Service: - lambda.amazonaws.com Version: 2012-10-17 ManagedPolicyArns: - arn:aws:iam::aws:policy/AWSLambdaExecute Path: / Policies: - PolicyName: "Assume-Management-Orgonisation-Data-Role" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: "sts:AssumeRole" Resource: Ref: RoleName - PolicyName: "S3-Access" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "logs:CreateLogGroup" - "logs:CreateLogStream" - "logs:PutLogEvents" - "logs:DescribeLogStreams" Resource: "arn:aws:logs:*:*:*" - PolicyName: "Sqs-Access" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: - sqs:SendMessage - sqs:ReceiveMessage - sqs:DeleteMessage - sqs:GetQueueAttributes Resource: "*" LambdaFunction: Type: AWS::Lambda::Function Properties: FunctionName: AWS-Orgonisation-Account-Collector Description: LambdaFunction of python3.8. Runtime: python3.8 Code: ZipFile: | import boto3 import logging import os def sqs_messege(account_id, QueueUrl): #posts messege to que client = boto3.client('sqs') response = client.send_message( QueueUrl=QueueUrl, MessageBody=account_id ) return response def org_accounts(): acount_ids = [] ROLE_ARN = os.environ['ROLE_ARN'] sts_connection = boto3.client('sts') acct_b = sts_connection.assume_role( RoleArn=ROLE_ARN, RoleSessionName="cross_acct_lambda" ) ACCESS_KEY = acct_b['Credentials']['AccessKeyId'] SECRET_KEY = acct_b['Credentials']['SecretAccessKey'] SESSION_TOKEN = acct_b['Credentials']['SessionToken'] # create service client using the assumed role credentials client = boto3.client( "organizations", region_name="us-east-1", #Using the Organization client to get the data. This MUST be us-east-1 regardless of region you have the lamda in aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, aws_session_token=SESSION_TOKEN, ) paginator = client.get_paginator("list_accounts") #Paginator for a large list of accounts response_iterator = paginator.paginate() for account in response_iterator: for ids in account['Accounts']: acount_ids.append(ids) logging.info("AWS Org data Gathered") return acount_ids def lambda_handler(event, context): account_info = org_accounts() for account in account_info: if account['Status'] == 'ACTIVE': try: account_id = account['Id'] sqs_messege(account_id, os.environ["SQS_URL"]) logging.info(f"SQS messege sent for {account_id} to TA") except Exception as e: pass logging.warning("%s" % e) else: logging.info(f"account {account['Id']} is not active") Handler: 'index.lambda_handler' MemorySize: 2688 Timeout: 600 Role: Fn::GetAtt: - LambdaRole - Arn Environment: Variables: SQS_URL: !Ref TaskQueue ROLE_ARN: !Ref RoleName CloudWatchTrigger: Type: AWS::Events::Rule Properties: Description: Monthly Name: !Sub "${CFDataName}-Monthly-Scheduler-For-Accounts" ScheduleExpression: "cron(30 12 L * ? *)" State: ENABLED Targets: - Arn: Fn::GetAtt: - LambdaFunction - Arn Id: WeeklyTriggerForGetAccounts TaskQueue: Type: AWS::SQS::Queue Properties: VisibilityTimeout: 300 ReceiveMessageWaitTimeSeconds: 20 DelaySeconds: 2 KmsMasterKeyId: "alias/aws/sqs" EventSourceMapping: Type: AWS::Lambda::EventSourceMapping Properties: EventSourceArn: Fn::GetAtt: - TaskQueue - Arn FunctionName: !Ref ECSLambdaARN EventPermission: Type: AWS::Lambda::Permission Properties: FunctionName: !GetAtt LambdaFunction.Arn Action: lambda:InvokeFunction Principal: events.amazonaws.com SourceAccount: !Ref 'AWS::AccountId' SourceArn: !GetAtt CloudWatchTrigger.Arn