Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding GCP admin_client helper. #349

Merged
merged 1 commit into from
Sep 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/train/transports/gcp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions test/unit/transports/gcp_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down