我试图在python 3.8中编写一个脚本,在云函数中停止所有实例(VM),无论区域,实例名称等。此外,我也在寻找指定的标签。但是我没有找到答案的地方,到处都是说我需要给项目id、地区和实例名。有跳过它的选项吗?
使用aggregatedList()和aggregatedList_next()方法列出所有区域中的所有实例。使用stop()方法终止实例。要理解aggregatedList()返回的数据,请研究REST API响应体。
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'v1', credentials=credentials)
# Project ID for this request.
project = "REPLACE_ME"
request = service.instances().aggregatedList(project=project)
while request is not None:
response = request.execute()
instances = response.get('items', {})
for instance in instances.values():
for i in instance.get('instances', []):
# Do something here to determine if this instance should be stopped.
# Stop instance
response = service.instances().stop(project=project, zone=zone, instance=i)
# Add code to check the response, see below
request = service.instances().aggregatedList_next(previous_request=request, previous_response=response)
示例代码检查response
stop()
返回的状态。您可能希望停止所有实例并将每个响应保存在一个列表中,然后处理该列表,直到所有实例都停止。
while True:
result = service.zoneOperations().get(
project=project,
zone=zone,
operation=response['name']).execute()
print('status:', result['status'])
if result['status'] == 'DONE':
print("done.")
break;
if 'error' in result:
raise Exception(result['error'])
time.sleep(1)