diff --git a/lib/train/transports/gcp.rb b/lib/train/transports/gcp.rb index e13f7932..42a759aa 100644 --- a/lib/train/transports/gcp.rb +++ b/lib/train/transports/gcp.rb @@ -6,6 +6,7 @@ require 'google/apis/compute_v1' require 'google/apis/storage_v1' require 'google/apis/iam_v1' +require 'google/apis/admin_directory_v1' require 'googleauth' module Train::Transports @@ -22,6 +23,7 @@ class Gcp < Train.plugin(1) # https://cloud.google.com/compute/docs/regions-zones/changing-default-zone-region # can also specify project via env var: option :google_cloud_project, required: false, default: ENV['GOOGLE_CLOUD_PROJECT'] + option :google_super_admin_email, required: false, default: ENV['GOOGLE_SUPER_ADMIN_EMAIL'] def connection(_ = nil) @connection ||= Connection.new(@options) @@ -63,6 +65,16 @@ def gcp_storage_client gcp_client(Google::Apis::StorageV1::StorageService) end + def gcp_admin_client + scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly'] + authorization = Google::Auth.get_application_default(scopes).dup + # Use of the Admin API requires delegation (impersonation). An email address of a Super Admin in + # the G Suite account may be required. + authorization.sub = @options[:google_super_admin_email] if @options[:google_super_admin_email] + Google::Apis::RequestOptions.default.authorization = authorization + gcp_client(Google::Apis::AdminDirectoryV1::DirectoryService) + end + # Let's allow for other clients too def gcp_client(klass) return klass.new unless cache_enabled?(:api_call) diff --git a/test/unit/transports/gcp_test.rb b/test/unit/transports/gcp_test.rb index 829de81d..3f89606c 100644 --- a/test/unit/transports/gcp_test.rb +++ b/test/unit/transports/gcp_test.rb @@ -146,6 +146,21 @@ def transport(options = nil) end end + describe 'gcp_admin_client' do + it 'test gcp_admin_client with caching' do + client = connection.gcp_admin_client + client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true + cache[:api_call].count.must_equal 1 + end + + it 'test gcp_admin_client without caching' do + connection.disable_cache(:api_call) + client = connection.gcp_admin_client + client.is_a?(Google::Apis::AdminDirectoryV1::DirectoryService).must_equal true + cache[:api_call].count.must_equal 0 + end + end + # test options override of env vars in connect describe 'connect' do let(:creds) do