Search code examples
google-sheetsgcloudservice-accounts

Retake ownership from service account


I've assigned ownership of one of my google sheets to a service account from a gcloud project I am working on (not a smart thing to do, I know...). How can I re-assign ownership of this sheet to my main user account?


Solution

  • If you have permissions on the service account (e.g. you're owner of the GCP project), you can use the command line tools to authenticate as the service account and modify the permissions there.

    Step by step process (you might have already some of those steps done):

    1. Download and install the GCP SDK:
    curl https://sdk.cloud.google.com | bash
    exec -l $SHELL
    gcloud init
    
    1. During the initialization, follow the steps to authenticate with the account owner of the GCP project, and select the project in question. You can ignore the rest of the steps.
    2. Create and download a key for the service account that is the current owner of the file (change the service account in this command):
    gcloud iam service-accounts keys create key --iam-account service_account_id@project_id.iam.gserviceaccount.com
    
    1. Hack the SDK to include the Drive scope:
    sed -i 's/\(^CLOUDSDK_SCOPES = (\)/\1"https:\/\/www.googleapis.com\/auth\/drive",/' $(gcloud info --format 'value(installation.sdk_root)')/lib/googlecloudsdk/core/config.py
    
    1. Activate the service account (change the service account in this command):
    gcloud auth activate-service-account service_account_id@project_id.iam.gserviceaccount.com --key-file key
    
    1. Make a call to the Drive API giving back the ownership (change the drive file ID and the new owner email address in this command):
    curl -H"Authorization: Bearer $(gcloud auth print-access-token)" https://www.googleapis.com/drive/v3/files/DRIVE_FILE_ID/permissions?transferOwnership=true -d '{"role":"owner","type":"user","emailAddress":"[email protected]"}' -H'content-type:application/json'
    

    After these steps, your regular email account should be the new owner.


    This is a pretty bad solution (hacking the SDK, etc..), but it's barely 7 bash commands, so I think it's likely the fastest/simplest one, at least for a one-off situation.

    If this happens often (I guess not), it's likely that a real script would be more useful.