LoginSignup
8
1

More than 1 year has passed since last update.

google api ruby client の service account の auth で任意の認証情報を指定する方法

Last updated at Posted at 2021-05-23

概要

google api を ruby から service account を使って実行するときは認証情報の入った json を指定するか

scope = 'https://www.googleapis.com/auth/androidpublisher'

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('/path/to/service_account_json_key.json'),
  scope: scope)

authorizer.fetch_access_token!

抜粋: https://github.com/googleapis/google-auth-library-ruby#example-service-account

ライブラリ側で指定されている特定の環境変数に値を設定する方法があります。

require 'googleauth'
require 'google/apis/drive_v3'

Drive = ::Google::Apis::DriveV3
drive = Drive::DriveService.new

# Auths with ENV vars:
# "GOOGLE_CLIENT_ID",
# "GOOGLE_CLIENT_EMAIL",
# "GOOGLE_ACCOUNT_TYPE", 
# "GOOGLE_PRIVATE_KEY"
auth = ::Google::Auth::ServiceAccountCredentials
  .make_creds(scope: 'https://www.googleapis.com/auth/drive')
drive.authorization = auth

list_files = drive.list_files()

抜粋: https://github.com/googleapis/google-auth-library-ruby#example-environment-variables

しかし、例えば Big Query 用、GA 用など複数のサービスアカウントがあり、それぞれの API を実行するときに使用するサービスアカウントを使い分けたいときがあります。

コンソールからダウンロードできる認証情報の記載された json で使い分ける方法もありますがリポジトリに json ファイルを置くわけにはいかないので json を何らかのクラウドストレージに置いて読み込んだり、環境変数に json を設定して読み込む方法も考えられますがどちらも少し面倒だと思います。

そこで Google::Auth::ServiceAccountCredentials に直に認証情報を渡す方法を紹介します。

やり方

client_emailprivate_key キーがある json を StringIO で作成して json_key_io 引数に渡せばできます。

sio = StringIO.new({client_email: ENV['GOOGLE_CLIENT_EMAIL_FOR_GA'], private_key: ENV['GOOGLE_PRIVATE_KEY_FOR_GA'].gsub(/\\n/, "\n")}.to_json)
auth = ::Google::Auth::ServiceAccountCredentials.make_creds(scope: 'https://www.googleapis.com/auth/analytics', json_key_io: sio)

参考: https://github.com/googleapis/google-auth-library-ruby/blob/master/lib/googleauth/json_key_reader.rb

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1