LoginSignup
1
3

More than 1 year has passed since last update.

Google Cloud SQLインスタンスを定期的に停止する

Last updated at Posted at 2022-06-29

概要

Google Cloud SQLのインスタンスを停止するための関数をCloud Functionsで作成し、Cloud Schedulerで定期実行するように設定しました。
今後も使いそうなので備忘録として残しておきます。

設定内容

Cloud Functions

Python3.9を使用しています。

requirements.txt
google-api-python-client
Oauth2client
main.py
import json
import os
import base64
import logging
import googleapiclient.discovery
from oauth2client.client import GoogleCredentials

from pprint import pprint

credentials = GoogleCredentials.get_application_default()
sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
instance = 'Cloud SQLのインスタンスID'
project = 'Cloud SQLのプロジェクトID'
body = body = {'settings': {'activationPolicy': 'NEVER',}} # インスタンスの停止

def stop_sql_database_instance(event):
    try:
        request = sqladmin.instances().patch(project=project, instance=instance, body=body)
        response = request.execute()
        pprint(response)
    except HttpError as err:
        logging.error("Could NOT run backup. Reason: {}".format(err))
        return "NG"
    else:
      logging.info("Backup task status: {}".format(response))
      return "OK"

Cloud Scheduler

設定項目の抜粋です。
以下のように設定しました。

設定項目 設定内容
頻度 unix-cron形式 例:0 20 * * *
タイムゾーン 日本標準時(JST)
ターゲットタイプ HTTP
URL Cloud FunctionsのトリガーURL
Authヘッダー OIDCトークンを追加
サービスアカウント Cloud Functions起動元権限のあるサービスアカウント
対象 Cloud FunctionsのトリガーURL

参考

インスタンスの起動、停止、再起動
https://cloud.google.com/sql/docs/mysql/start-stop-restart-instance?hl=ja#rest-v1beta4_1
Method: instances.patch
https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/instances/patch
開発費用の削減: Cloud SQL インスタンスの起動と停止をスケジュールする
https://cloud.google.com/blog/ja/topics/developers-practitioners/lower-development-costs-schedule-cloud-sql-instances-start-and-stop

1
3
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
1
3