0
0

More than 1 year has passed since last update.

GoogleCloud(GCP)のCloud Functions上で動作するPythonからGCE(Google Compute Engine)を起動・停止させる

Posted at

説明

タイトルにある通りです。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は起動したり、停止したりします

image.png

めちゃくそテキトーですが、役に立てばうれしいです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0