def share_grants_to_linked_accounts()

in service-catalog-and-license-manager-entitlement/handler.py [0:0]


def share_grants_to_linked_accounts(event):
    """
    Purpose: Share grants to the linked accounts. 
    """
    
    message = event['detail']['responseElements']
    
    product_name = message['productViewDetail']['productViewSummary']['name']
    
    logging.info('Find license for product name %s', product_name)
    
    mp_licenses = boto3.client('license-manager').list_received_licenses()
    mp_license = next(filter(lambda obj: obj.get('ProductName') == product_name, mp_licenses['Licenses']), None)
    
    logging.info('License found: %s', mp_license)


    org = boto3.client('organizations')

    paginator = org.get_paginator('list_accounts')
    account_iterator = paginator.paginate()
    current_account_id = boto3.client("sts").get_caller_identity()["Account"]
    
    for accounts in account_iterator:        
        for account in accounts['Accounts']:
            print(account) # print the account
            
            if account['Id'] == current_account_id:
                continue
            
            try:
                
                create_grant_response = boto3.client('license-manager', region_name='us-east-1').create_grant(
                            ClientToken= f"token_{round(time.time() * 1000)}",
                            GrantName= f"{product_name}-{account['Id']}",
                            LicenseArn=mp_license['LicenseArn'],
                            Principals=[
                                f"arn:aws:iam::{account['Id']}:root",
                            ],
                            HomeRegion='us-east-1',
                            AllowedOperations= ["CheckoutLicense", "CheckInLicense",
                                 "ExtendConsumptionLicense", "ListPurchasedLicenses"]
                        )
                logging.info('Grant Created: %s', create_grant_response)

                response_create_version = boto3.client('license-manager', region_name='us-east-1').create_grant_version(
                    ClientToken=f"token_{round(time.time() * 1000)}",
                    GrantArn=create_grant_response['GrantArn'],
                    Status='ACTIVE'
                )
                
                logging.info('Grant Version Created: %s', response_create_version)
                

                        
            except ClientError as e:
                logging.error(e)