Search code examples
pythonapigoogle-cloud-platformgoogle-python-apigoogle-cloud-iam

Issue Deleting Google Compute Account through API using Python


I was able to piece together a Python script to interact with the Google API Library using information from here and here. The code below is working and I'm able to list all accounts within a particular Project. See below:

Code:

import os
from googleapiclient import discovery
from gcp import get_key

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()

service = discovery.build('cloudresourcemanager', 'v1')
project_id = 'test-buckets'

get_iam = {}

request = service.projects().getIamPolicy(resource=project_id, body=get_iam)
response = request.execute()

bindings = response['bindings']

for binding in bindings:
    for member in binding['members']:
        print(member)

Output:

ssh://[email protected]:22/home/xxxx/venv/bin/python3.4 -u /home/xxxx/scratch.py

serviceAccount:[email protected]
serviceAccount:[email protected]
user:[email protected]

Now, I'm trying to leverage the API to delete specific accounts that are not needed (script below), however, I can't seem to get the the API to work. I'm using the Google API Library again here, but it doesn't seem to be working. I'm not sure what I'm doing wrong. Any help you can offer is greatly appreciated.

Code:

import os
from pprint import pprint
from googleapiclient import discovery
from gcp import get_key

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()

service = discovery.build('cloudresourcemanager', 'v1')
project_id = 'test-buckets'

service_account = 'projects/xxxxxxx/serviceAccounts/[email protected]'

request = service.projects().delete(name=service_account, body={})
response = request.execute()

pprint(response)

Output:

ssh://[email protected]:22/home/xxxx/venv/bin/python3.4 -u /home/xxxx/scratch2.py
Traceback (most recent call last):
  File "/home/xxxx/scratch2.py", line 13, in <module>
    request = service.projects().delete(name=service_account, body={})
  File "/home/xxxx/venv/lib/python3.4/site-packages/googleapiclient/discovery.py", line 722, in method
    raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "body"

Process finished with exit code 1

Solution

  • I figured out that I was using the wrong API when building the service too. Below is the corrected code:

    service = discovery.build('iam', 'v1')
    request = service.projects().serviceAccounts().delete(name=project_name)
    response = request.execute()