LoginSignup
0
0

More than 3 years have passed since last update.

Google のプリエンプティブル VM(Preemptible VM) の状態を監視し、落ちていたら実行する

Last updated at Posted at 2020-06-14

VM を startVM するだけのサンプルはたくさん見つかったけど、VM が実際に実行状態(RUNNING)なのかどうかをチェックしながら落ちていたら実行するサンプルが全然見つからなかったので、API を調査して実装した。

ランタイム:node.js 10

node.js
/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.startVM = (req, res) => {
  const Compute = require('@google-cloud/compute');
  const compute = new Compute();
  const zone = compute.zone('your zone id'); // asia-northeast1-c とか
  const vm = zone.vm('your vm name'); // my-vm-name とか

  vm.get(function(err, data, apiResponse) {
    if (data.metadata.status == 'RUNNING') {
      console.log('VM is already running.')
    } else {
      console.log('VM is not running.')

      vm.start(function(err, operation, apiResponse) {
      });
    }
  });

  res.status(200).send('ok');
};
package.json
{
  "name": "適当な名前",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/compute": "1.2.0"
  }
}

あとは、トリガーの URL を Cloud Functions に設定して好きな日時(5分間隔とか)で実行するだけ

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