如何使用 python 启动多个计算实例

How to start multiples compute instances with python

有人在这里分享了下面的代码 (),我做了一些改编,它非常适合我启动一个虚拟机。我想知道是否可以修改此代码以在同一函数中启动多个实例? 这是代码:

from googleapiclient import discovery
 
service = discovery.build('compute', 'v1')
 
def autostart_vm(request):
 
        # Project ID for this request.
        project = 'secret-metrics-278618'
 
        # The name of the zone for this request.
        zone = 'us-central1-a' 
 
        # Name of the instance resource to start.
        instance = 'devops1'
        instance2 = 'devops-2'
        
 
        request = service.instances().start(project=project, zone=zone, instance=instance)
        response = request.execute()
        
 
        print('VM Instance started')

虽然你必须做出调整,但这是可能的。来自instances().start()的描述:

Starts an instance that was stopped using the instances().stop method. For more information, see Restart an instance.

这意味着您必须像这样迭代该方法(假设您的实例位于类似的项目和区域中):

# Name of the instance resource to start.
instanceList = ['devops1', 'devops-2']

for i in instanceList:   
  request = service.instances().start(project=project, zone=zone, instance=i)
  response = request.execute()
  print('VM instance '+ i + ' started')