@@ -0,0 +1,2022 @@
+from functools import reduce%0Afrom typing import cast, MutableSequence, Sequence%0Aimport csv%0Afrom looker_sdk import client, models%0A%0A%22%22%22%0AThe purpose of this script is to parse a CSV file containing a Role name in the first column%0Aand a Group name in the second column, and update role/group membership accordingly. It will%0Aalso remove any individual users assigned to the roles listed in the CSV.%0A%0AContents of example roles-groups.csv:%0ARole 1,Group A%0ARole 1,Group B%0ARole 2,Group C%0ARole 2,Group D%0ARole 3,Group E%0ARole 3,Group F%0A%0AThe result of running this script will be that Role 1 will be associated to Group A and Group B,%0ARole 2 will be associated to Group C and Group D, and Role 3 will be associated to Group E and%0AGroup F. If individual users were associated to these three roles, they will be removed.%0A%22%22%22%0A%0Asdk = client.setup(%22looker.ini%22)%0Afilename = 'roles-groups.csv'%0Acached_roles = %7B%7D%0A%0A%0Adef load_group(group):%0A    groups = sdk.search_groups(name=group, limit=1)%0A    if groups:%0A        return groups%5B0%5D%0A%0A%0Adef load_role(role):%0A    # Don't make a GET /roles/search request for every line%0A    if role in cached_roles.keys():%0A        return cached_roles%5Brole%5D%0A%0A    roles = sdk.search_roles(name=role, limit=1)%0A    if roles:%0A        roles%5B0%5D.group_ids = %5B%5D%0A        cached_roles%5Brole%5D = roles%5B0%5D%0A        return roles%5B0%5D%0A%0A%0Adef main():%0A    f = open(filename, 'r', encoding='utf-8-sig')%0A    csv_reader = csv.reader(f, delimiter=',')%0A%0A    for line in csv_reader:%0A        print(%22.%22, end='')%0A        role = load_role(line%5B0%5D)%0A        group = load_group(line%5B1%5D)%0A        if role and group:%0A            cached_roles%5Bline%5B0%5D%5D.group_ids.append(group.id)%0A%0A    for role in cached_roles:%0A        sdk.set_role_groups(role_id=cached_roles%5Brole%5D.id, body=cached_roles%5Brole%5D.group_ids)%0A        sdk.set_role_users(role_id=cached_roles%5Brole%5D.id, body=%5B%5D)%0A        print()%0A        print(%22Updated '%22 + role + %22' role to remove individual users and associated these group_ids to it instead:%22)%0A        print(cached_roles%5Brole%5D.group_ids)%0A%0A%0Amain()%0A

Create assign_groups_to_role.py