TL;DR
- googleapisを使って、G Suiteの Groupを作成できるようにした
- 公式のドキュメントにはnodejsでの実装方法が無かったので自分で実装した
- よってこれが最適な方法かは分からない
- G Suiteの特権管理者の権限が付与されている必要がある
https://developers.google.com/admin-sdk/directory/v1/guides/delegation
大体このドキュメントに沿って作った
手順
- GCP上にサービスアカウントを作成する
- G SuiteのAdmin consoleにて、GCPのサービスアカウントに G Suite APIを叩くための権限を付与する
- Groupを作成するコードを実装する
GCP上にサービスアカウントを作成する
- GCP consoleにてservice accountのページを開き、新しく service accountを作成する
- Enable Google Apps Domain-wide Delegation にチェックを入れる
- 鍵を作ってDLする
- 鍵のjsonを開き、client_idをメモしておく

GCPのサービスアカウントにG Suiteの権限を付与する
- G Suiteのadmin consoleを開く
- Advanced settingsを選ぶ
- AuthenticationセクションのManage API client accessを選ぶ
- Client Nameの部分にサービスアカウント作成時にメモしておいた client idを設定する
- scopesの部分に
https://www.googleapis.com/auth/admin.directory.group
を設定する- APIに必要な権限はこのドキュメント から確認できる
- authorize を押す

Groupを作成するコード
create_group.ts
import { google } from "googleapis";
import path from "path";
async function main() {
const jwtClient = new google.auth.JWT({
keyFile: path.join(__dirname, "credentials.json"),
scopes: ['https://www.googleapis.com/auth/admin.directory.group'],
subject: process.env.SUBJECT
});
await jwtClient.authorize()
const admin = google.admin({
version: 'directory_v1',
auth: jwtClient
});
const param = {
requestBody: {
email: 'sample-group@xxx.jp',
name: 'sample-group',
description: 'hogehoge'
}
};
const response = await admin.groups.insert(param);
console.log(response.data);
}
main();
jwtClient
を生成する際の subject
には操作権限の委任を行うユーザのメールアドレスを渡す必要があり、監査ログ等にはここで指定したユーザの名前が記録されます。
結果
$ npx ts-node create_group.ts
{ kind: 'admin#directory#group',
id: 'xxx',
etag: '"xxx"',
email: 'sample-group@xxx.jp',
name: 'sample-group',
description: 'hogehoge',
adminCreated: true }
こんな感じでグループができました