GCE(google compute engine)インスタンスの自動停止・スケジュール

GCE(google compute engine)で、利用しない時間にインスタンスを停止したい。
そのために、GAE(google app engine)で、起動・停止用アプリケーションを設置し、それらのアプリケーションをGAEのcronで定期実行する。

目次
☆GAEとは
☆必要ファイル
 -crom.yaml
-app.yaml
-実行スクリプト(instance.py)
-libs
☆アプリケーションのデプロイ

―――――――――

☆GAEとは
App Engineはインフラ部分を管理せずにWEBアプリを実装できる仕組み
過去記事を参照
http://tug-uca.hatenablog.com/entry/2018/06/12/182533


☆必要ファイル
cloud shell上で必要ファイルを以下のように配置する。

任意のフォルダ
├─ lib
|   └─ ....
└─ cron.yaml
└─ app.yaml
└─ 実行スクリプト(instance.py)

本記事の大部分は以下の記事を参考にしている。
https://qiita.com/hatappi/items/a756ea8fd29d7d802e13


-crom.yaml
起動時間、停止時間を変えたいときは、このファイルを変更する。
フォーマット:https://cloud.google.com/appengine/docs/standard/python/config/cron#Python_app_yaml_The_schedule_format

cron:
- description: "instance start"
  url: /instance/start
  schedule: every day 09:00
  timezone: Asia/Tokyo
- description: "instance stop"
  url: /instance/stop
  schedule: every day 22:00
  timezone: Asia/Tokyo


-app.yaml

runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /instance/start
  script: instance.app
  login: admin
- url: /instance/stop
  script: instance.app
  login: admin

-実行スクリプト(instance.py)

扱うインスタンスを追加・変更するときは[インスタンス名のリスト]を変更する。

#!/usr/bin/python
# -*- coding: utf-8 -

import sys
sys.path.insert(0, 'libs')
import webapp2
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build

project = 'プロジェクトID'
zone = 'インスタンスのあるゾーン'
instance_names = [インスタンス名のリスト]

credentials = GoogleCredentials.get_application_default()
compute = build('compute', 'v1', credentials=credentials)

# 開始用のHandler class
class InstanceStartHandler(webapp2.RequestHandler):
    def get(self):
        print 'instance start process start'

        for instance_name in instance_names:
            # project, zone, instance名からインスタンスの情報を取得
            instance = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
            print '%s is %s' %(instance['name'], instance['status'])
            # インスタンスが停止している場合は開始処理を行う
            if instance['status'] == 'TERMINATED':
                print 'instance %s start......' %(instance['name'])
                compute.instances().start(project=project, zone=zone, instance=instance['name']).execute()

            print 'instance start process end'

# 停止用のHandler class
class InstanceStopHandler(webapp2.RequestHandler):
    def get(self):
        print 'instance stop process start'

        for instance_name in instance_names:
            # project, zone, instance名からインスタンスの情報を取得
            instance = compute.instances().get(project=project, zone=zone, instance=instance_name).execute()
            print '%s is %s' %(instance['name'], instance['status'])
            # インスタンスが動いている場合は止める処理を行う
            if instance['status'] == 'RUNNING':
                print 'instance %s stop......' %(instance['name'])
                compute.instances().stop(project=project, zone=zone, instance=instance['name']).execute()
            print 'instance stop process end'
                  
# app.yamlで設定したURLと実行するclassのセットを配列で定義する
app = webapp2.WSGIApplication(
        [
            ('/instance/start', InstanceStartHandler),
            ('/instance/stop', InstanceStopHandler)
        ],
        debug=True
        )


-libs
標準のライブラリ以外はディレクトリlibsに入れておく必要がある。
https://qiita.com/cocodrips/items/3bc82b1136a2bd7a7997

pip install -t libs google-api-python-client
pip install -t libs oauth2client


☆アプリケーションのデプロイ

cloud shell上で以下のコマンドを実行する
アプリケーションのデプロイ

gcloud app deploy app.yaml

cronのデプロイ

gcloud app deploy cron.yaml

成功していれば、タスクキューのcronジョブが設定される。
f:id:Tug-uca:20180615154543p:plain