Using the service account to enable access to cloud storage

This is part of the writeup on Using Google Cloud Storage with Apps Script. In Enabling APIs and OAuth2 I showed what needed to be done in the developer console to get credentials to use in your Script to access Cloud Storage. Now we'll move on to coding and how to use the service account from your script


You'll need the cGoa library, or some other library if you are using. It can be included in your project with this key


or the code is on github if you prefer.

Once off setup

The script properties are used to automatically renew oauth2 tokens when required, so the entire OAuth2 process is invisible to you. But first, you need to populate the script Properties by running a piece of code one time. You can delete it from your project once you've run it.  

You need to make two changes to tailor it for you. 
  • the fileId - set this to the file id of the JSON credentials file you downloaded from the console and moved to drive
  • packageName - this is how you will refer to this package in the future. I usually match the package name to the name I gave to the service account in the console, but you can call it what you like.
function oneOffSetting() { 
  // Provoke Driveapp.getFileById() permission dialog with this comment
  // used by all using this script
  var propertyStore = PropertiesService.getScriptProperties();
  // service account for cloud vision
  cGoa.GoaApp.setPackage (
    propertyStore , 
    cGoa.GoaApp.createServiceAccount (DriveApp , {
      packageName: 'xliberation-store',
      scopes : cGoa.GoaApp.scopesGoogleExpand (['cloud-platform']),

And that's all there is to it. Now you can delete this function and start using these credentials in your script, as described in GcsStore overview - Google Cloud Storage and Apps Script

For more like this, see Google Apps Scripts snippets. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.