Home Auto Expiring Google Group Membership
Post
Cancel

Auto Expiring Google Group Membership

Are you looking forward to setting up Google Workspace Services such as Google Meet to auto-expire for the users? Here’s a way to reduce time and administration costs by automating some group management task. This enables admins to set an amount of time that users and service accounts are members of a group. Once the specified time has passed, users will be removed from the group automatically. Automatic membership expiration can help reduce the administrative overhead for managing groups and can help ensure group membership is limited to the members that need access.

Prerequisites

This feature is only available to Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education, and Cloud Identity Premium accounts.

1
$ pip install — upgrade google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

Straight to the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# This script assumes the following:
# You have enabled the relevant service (E.g Google Meets in my case) for the declared group_id
# You have enabled the relevant APIs and API accees is not blocked on the tenancy
# You have enabled the Cloud Identity API.
# pip install --upgrade google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

#run the code:
#python3 expiringGroupMemberships.py

# If modifying SCOPES, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/cloud-identity.groups']
group_id = '[email protected]' #group for which the service is enabled
member_keys = ['[email protected]','[email protected]'] #emails of users who want to have auto expiring membership to the group
expiry_time = "2021-11-19T14:10:23Z" #expiry time - A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".

def create_google_group_membership(service, group_id, member_keys):
  param = "&groupKey.id=" + group_id
  try:
    lookupGroupNameRequest = service.groups().lookup()
    lookupGroupNameRequest.uri += param
    # Given a group ID and namespace, retrieve the ID for parent group
    lookupGroupNameResponse = lookupGroupNameRequest.execute()
    groupName = lookupGroupNameResponse.get("name")
    print (f"########\n{groupName}\n##########")
    # Create a membership object with a memberKey and a single role of type MEMBER
    for member_key in member_keys:
        membership = {
          "preferredMemberKey": {
            "id": member_key
            },
          "roles" : {
            "name" : "MEMBER",
            "expiryDetail": {
              "expireTime": expiry_time
            }
          }
        }
        # Create a membership using the ID for the parent group and a membership object
        response = service.groups().memberships().create(parent=groupName, body=membership).execute()
        print (response)
  except Exception as e:
    print (e)


def main():
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        service = build('cloudidentity', 'v1', credentials=creds)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_console()
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
        service = build('cloudidentity', 'v1', credentials=creds)

    create_google_group_membership(service, group_id, member_keys)



if __name__ == '__main__':
    main()

Setup Email notification

Email notifications are automatically sent to all group owners when memberships are about to expire. Notifications are sent 72 hours before expiration or immediately if the membership will expire before 72 hours when it is set.

Thank you

Source

This post is licensed under CC BY 4.0 by the author.