问题使用Python通过API删除Google Compute帐户

时间:2018-01-04 17:40:26

标签: python api google-cloud-platform google-python-api google-cloud-iam

我能够使用来自herehere的信息拼凑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

2 个答案:

答案 0 :(得分:0)

也许它的答案有点太迟了,但我认为代码中唯一的错误是这行代码:

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操作的响应没有内容。

答案 1 :(得分:0)

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

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