使用 Python 通过 API 删除 Google 计算帐户

Issue Deleting Google Compute Account through API using Python

我能够使用 here and here 中的信息拼凑出一个 Python 脚本来与 Google API 库进行交互。下面的代码正在运行,我能够列出特定项目中的所有帐户。见下文:

代码:

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)

输出:

ssh://xxxx@x.x.x.x:22/home/xxxx/venv/bin/python3.4 -u /home/xxxx/scratch.py

serviceAccount:xxxxxxxxxxx-compute@developer.gserviceaccount.com
serviceAccount:xxxxxxxxxxx@xxxxxxxxxxx.iam.gserviceaccount.com
user:xxxx@.xxxxx.com

现在,我正在尝试利用 API 删除不需要的特定帐户(下面的脚本),但是,我似乎无法让 API 工作.我再次使用 Google API 库 here,但它似乎不起作用。我不确定我做错了什么。非常感谢您提供的任何帮助。

代码:

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/test-delete@test-buckets.iam.gserviceaccount.com'

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

pprint(response)

输出:

ssh://xxxx@x.x.x.x: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

也许现在回答有点晚了,但我认为你的代码中唯一的错误是这行代码:

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

其实应该是这样的:

request = service.projects().delete(name=service_account)

正如您在共享的错误中看到的那样,TypeError: Got an unexpected keyword argument "body",因此 body 不是此处可接受的参数。在任何情况下,打印 pprint(response) 中的响应可能不会输出任何内容,因为对 DELETE 操作的响应没有内容。

我发现我在构建服务时也使用了错误的 API。下面是更正后的代码:

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