0

So I'm writing a script to batch delete users from a Google Apps for Education domain. The code looks like this:

#! /usr/bin/env ruby
require 'google/api_client'
require 'csv'

service_account_email = 'XXXXXXX@developer.gserviceaccount.com'
key_file = 'key.p12'
key_secret = 'notasecret'
admin_email = 'XXX@xxx'

# Build the API Client object
client = Google::APIClient.new(
  :application_name => 'XXX',
  :application_version => '0.1'
)
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => 'https://www.googleapis.com/auth/admin.directory.user',
  :issuer => service_account_email,
  :signing_key => key,
  :person => admin_email,
)
client.authorization.fetch_access_token!
directory = client.discovered_api('admin', 'directory_v1')

# Reads and parses CSV input into a hash
# Takes file path as an argument
def import_csv(file)
  csv = CSV.new(
    File.open(file).read,
    :headers => true,
    :header_converters => :symbol
  )

  return csv.to_a.map {|row| row.to_hash}
end

users_to_delete = import_csv('accounts.csv')

puts 'Preparing to delete users...'

users_to_delete.each_slice(1000) do |chunk|  
  directory.batch do |directory|
    chunk.each do |user|
      client.execute!(
        :api_method => directory.users.delete,
        :parameters => { :userKey => user[:emailaddress].downcase }
      )
    end
  end
end

puts 'Users successfully deleted!'

When I run the script without the two outer batch blocks, the script runs perfectly (although incredibly slowly).

What I want to know is what I need to change to stop giving me the undefined method error on the 'batch' method for the directory API. In examples in Google's documentation, I've noticed that they call the API differently (zoo = Google::Apis::ZooV1::ZooService.new instead of zoo = client.discovered_api('zoo', 'v1')). I don't see how that would make a difference though.

1 Answers1

1

You can do achieve it this way:

client = Google::APIClient.new(
 :application_name => 'XXX',
 :application_version => '0.1'

)

directory = client.discovered_api('admin', 'directory_v1')
batch = Google::APIClient::BatchRequest.new do |result|
 puts result.data
end
batch.add(:api_method => directory.users.delete,:parameters => { :userKey =>       user[:emailaddress].downcase })
client.execute(batch)
Aravind Raju
  • 61
  • 1
  • 5