def _check_table_managed_by_iam_access_and_enable_opt_in()

in migration/bring-your-own-gdc-assets/bring_your_own_gdc_assets.py [0:0]


def _check_table_managed_by_iam_access_and_enable_opt_in(database_name, table_name, role_arn, lf_client):
    '''
    Checks if the table is managed by IAM access. If it is, then enables hybrid mode for the table to allow Lake Formation permissions to work.
    '''
    try:
        table_access = lf_client.list_permissions(
            Resource={
                'Table': {
                    'DatabaseName': database_name,
                    'Name': table_name
                }
            },
            Principal={
                'DataLakePrincipalIdentifier': 'IAM_ALLOWED_PRINCIPALS'
            }
        ).get('PrincipalResourcePermissions', [])

        if table_access:
            print(f"Glue table: {database_name}.{table_name} is managed via IAM access")
            tb_opt_in = lf_client.list_lake_formation_opt_ins(
                Principal={
                    'DataLakePrincipalIdentifier': role_arn
                },
                Resource={
                    'Table': {
                        'DatabaseName': database_name,
                        'Name': table_name
                    }
                }
            ).get('LakeFormationOptInsInfoList', [])

            if tb_opt_in:
                print(f"Principal: {role_arn} is already opted-in to {database_name}.{table_name}")
            else:
                lf_client.create_lake_formation_opt_in(
                    Principal={
                        'DataLakePrincipalIdentifier': role_arn
                    },
                    Resource={
                        'Table': {
                            'DatabaseName': database_name,
                            'Name': table_name
                        }
                    }
                )
                print(f"Successfully created Lake Formation opt-in for {database_name}.{table_name}")
        else:
            print(f"Glue table: {database_name}.{table_name} is already managed via LakeFormation")

    except Exception as e:
        print(f"Error checking whether glue database and table {database_name}.{table_name} is managed by IAM access and setting opt in : {str(e)}")
        raise e