Skip to content

Instantly share code, notes, and snippets.

@austinsonger
Last active December 13, 2024 06:23
Show Gist options
  • Save austinsonger/c941884d50b46c93e258f00a85785475 to your computer and use it in GitHub Desktop.
Save austinsonger/c941884d50b46c93e258f00a85785475 to your computer and use it in GitHub Desktop.
Automation of Google Group Creation and Membership Management Using Google Apps Script

This script is designed to automate two main tasks using Google's Admin SDK and Apps Script: creating a new Google Group and adding a member to that group. It consists of a main function createGroupAndAddMember() and a helper function getOAuthService(). Here’s a breakdown of what each part does:

  1. Initialization and Configuration:

    • groupEmail, groupName, description: These variables are placeholders for the new group’s email, name, and description, respectively. You should replace them with actual values.
    • memberEmail: Email of the member to be added to the newly created group.
  2. OAuth Service Setup (getOAuthService()):

    • Retrieves a stored service account key from the script's properties.
    • Parses and uses this key to configure OAuth2 service with necessary details (client ID, private key, client email) and the required scopes which allow managing Google Groups and their members.
  3. OAuth Access Check:

    • Before proceeding, the script checks if the OAuth service has access. If not, it logs a URL for manual authorization.
  4. Creating the Group:

    • Constructs a payload with the group's details.
    • Sends a POST request to the Google Admin SDK API to create a group using UrlFetchApp.fetch().
    • Logs the success message with the created group's email.
  5. Adding a Member to the Group:

    • Constructs a payload with the member's email and role.
    • Sends another POST request to add the specified email as a member to the newly created group.
    • Logs the success message with the added member's email.
{
"timeZone": "America/Denver",
"dependencies": {
"libraries": [
{
"userSymbol": "OAuth2",
"version": "43",
"libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
}
]
},
"exceptionLogging": "STACKDRIVER",
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/admin.directory.group",
"https://www.googleapis.com/auth/admin.directory.group.member"
],
"runtimeVersion": "V8"
}
// Create a Google Group and add a member
function createGroupAndAddMember() {
const groupEmail = '<PlaceHolder>@cirrusmd.com'; // Replace with the desired group email
const groupName = '<New Group Name>'; // Replace with the group name
const description = 'This is a new group created via Apps Script';
const memberEmail = '[email protected]';
const service = getOAuthService();
if (!service.hasAccess()) {
Logger.log('Authorization required. Visit: %s', service.getAuthorizationUrl());
return;
}
// Step 1: Create the Group
const groupPayload = {
email: groupEmail,
name: groupName,
description: description,
};
const createGroupUrl = 'https://admin.googleapis.com/admin/directory/v1/groups';
const createGroupResponse = UrlFetchApp.fetch(createGroupUrl, {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
},
payload: JSON.stringify(groupPayload),
});
const createdGroup = JSON.parse(createGroupResponse.getContentText());
Logger.log(`Group created successfully: ${createdGroup.email}`);
// Step 2: Add a Member to the Group
const memberPayload = {
email: memberEmail,
role: 'MEMBER', // Options: MEMBER, OWNER, MANAGER
};
const addMemberUrl = `https://admin.googleapis.com/admin/directory/v1/groups/${groupEmail}/members`;
const addMemberResponse = UrlFetchApp.fetch(addMemberUrl, {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
},
payload: JSON.stringify(memberPayload),
});
const addedMember = JSON.parse(addMemberResponse.getContentText());
Logger.log(`Member added successfully: ${addedMember.email}`);
}
// OAuth service for Admin SDK
function getOAuthService() {
const key = PropertiesService.getScriptProperties().getProperty('SERVICE_ACCOUNT_KEY');
if (!key) {
throw new Error('SERVICE_ACCOUNT_KEY is missing in Script Properties.');
}
const serviceAccountKey = JSON.parse(Utilities.newBlob(Utilities.base64Decode(key)).getDataAsString());
return OAuth2.createService('AdminSDK')
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(serviceAccountKey.private_key)
.setClientId(serviceAccountKey.client_id)
.setIssuer(serviceAccountKey.client_email)
.setScope('https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.group.member');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment