selmertsxの素振り日記

ひたすら日々の素振り内容を書き続けるだけの日記

G Suite Domain-Wide Delegationを使ってG SuiteのGroupを作成する

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をメモしておく

スクリーンショット 2018-10-16 16.41.37.png

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 を設定する
  • authorize を押す

スクリーンショット 2018-10-16 20.44.57.png

Groupを作成するコード

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.readonly'],
    subject: process.env.SUBJECT
  });

  await jwtClient.authorize()

  const admin = google.admin({
    version: 'directory_v1',
    auth: jwtClient
  });

  const response = await admin.groups.list({ domain: process.env.DOMAIN });
  console.log(response.data);
}

main();

結果

$ 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 }

こんな感じでグループができました