説明
タイトルにある通りです。GoogleCloudのpython用のAPIの説明が分かりづらかったので、載せました。
実行環境
GoogleCloudのCloudFunctions(第二世代)
プログラム
pythonのプログラム。main関数を適宜変更してください。
main.py
import functions_framework
from google.auth import compute_engine
from google.cloud import compute_v1
@functions_framework.http
def main(request):
# project名
project = "xxxxxxxxxxxx"
# ゾーン名(リージョン)
zone = "asia-northeast1-c"
# 仮想マシン名
instance ="xxxxxxxxxxxxxx"
# 仮想マシンを止めるとき
stop_VM(project,zone,instance)
# 仮想マシンを起動させるとき
start_VM(project,zone,instance)
return "200"
def start_VM(project,zone,instance):
credentials = compute_engine.Credentials()
Instance = compute_v1.InstancesClient(credentials=credentials)
Instance.start(project=project,instance=instance,zone=zone)
def stop_VM(project,zone,instance):
credentials = compute_engine.Credentials()
Instance = compute_v1.InstancesClient(credentials=credentials)
Instance.stop(project=project,instance=instance,zone=zone)
ライブラリ関連
requirements.txt
functions-framework==3.*
google-api-core
google-auth
google-cloud-appengine-logging
google-cloud-audit-log
google-cloud-billing-budgets
google-cloud-compute
google-cloud-core
google-cloud-error-reporting
google-cloud-logging
googleapis-common-protos
grpc-google-iam-v1
grpcio
grpcio-status
実行方法
Cloud Functionsにデプロイしてください。APIの認証など適宜お願いします。
その後、以下のページへ行きCLOUD SHELLでテストを押せばターミナルが開き、実行できます。
成功すれば、対象のGCEは起動したり、停止したりします
めちゃくそテキトーですが、役に立てばうれしいです