python 3.7
requiremets.txt
google-api-python-client==1.7.9
oauth2client==4.1.3
main.py
import time
from googleapiclient.discovery import build, Resource
from oauth2client.client import GoogleCredentials
def start(project, zone, instance_name):
credentials: GoogleCredentials = GoogleCredentials.get_application_default()
compute: Resource = build('compute', 'v1', credentials=credentials)
instance: dict = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
result: dict = compute.instances().start(project=project, zone=zone, instance=instance['name']).execute()
# Wait Running
while True:
instance: dict = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
print(instance["status"])
# TERMINATED -> STAGING -> RUNNING
if instance["status"] == "RUNNING":
break
time.sleep(5)
def stop(project, zone, instance_name):
credentials: GoogleCredentials = GoogleCredentials.get_application_default()
compute: Resource = build('compute', 'v1', credentials=credentials)
instance: dict = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
result: dict = compute.instances().stop(project=project, zone=zone, instance=instance['name']).execute()
# Wait Terminated
while True:
instance: dict = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
print(instance["status"])
# RUNNING -> STOPPING -> TERMINATED
if instance["status"] == "TERMINATED":
break
time.sleep(5)
if __name__ == "__main__":
project = 'xxx'
zone = 'yyy'
instance_name = "zzz"
start(project, zone, instance_name)
stop(project, zone, instance_name)
Recommended Posts