node.js - 如何使用 Google Cloud Function 启动和停止 vm 实例?
问题描述
我正在尝试通过云功能启动和停止现有的谷歌云计算虚拟机。
我在文档中找到了这个,但我不确定这将如何作为云功能工作。身份验证如何工作?如何安装 Node.js 库?
// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Compute Engine API
// and check the quota for your project at
// https://console.developers.google.com/apis/api/compute
// 2. This sample uses Application Default Credentials for authentication.
// If not already done, install the gcloud CLI from
// https://cloud.google.com/sdk and run
// `gcloud beta auth application-default login`.
// For more information, see
// https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the Node.js client library by running
// `npm install googleapis --save`
const {google} = require('googleapis');
var compute = google.compute('v1');
authorize(function(authClient) {
var request = {
// Project ID for this request.
project: 'my-project', // TODO: Update placeholder value.
// The name of the zone for this request.
zone: 'my-zone', // TODO: Update placeholder value.
// Name of the instance resource to start.
instance: 'my-instance', // TODO: Update placeholder value.
auth: authClient,
};
compute.instances.start(request, function(err, response) {
if (err) {
console.error(err);
return;
}
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
});
});
function authorize(callback) {
google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}).then(client => {
callback(client);
}).catch(err => {
console.error('authentication failed: ', err);
});
}
谢谢您的帮助!
解决方案
目前 GCP 中有一个新功能。Cloud Scheduler,允许用户在 GCE 虚拟机中安排启动和停止。
Cloud Scheduler是一个完全托管的企业级 cron 作业调度程序。
启动/停止 GCE VM Cloud Scheduler 使用 Cloud Function 和 Pub/Sub。
有一个完整的文档指南,使用提供的 Cloud Functions 使用 Cloud Scheduler 调度计算实例(在那里您会找到一个 start instance .js function sample 1和一个 stop instance function sample 2)。
按照该指南,您将能够使用 Google Cloud Function 来启动和停止 GCE 实例。
推荐阅读
- flutter - 如何在颤动中创建增加日期的列表?
- javascript - Firebase 用户验证电子邮件操作 URL 到自定义 URL
- sharepoint-online - 添加和更新功能在使用 SPfx PnP.js 编码的 SharePoint 在线列表中不起作用
- c# - LINQ 包含查询的子集
- typescript - 提取属性时保留对象属性的可为空指定
- node.js - 如何使用 NodeJS coinbase pro api 从正文键中获取价格
- node.js - 如何在多个集合上查找并将我们得到的响应传递给路由
- amazon-web-services - 如何使用 AWS appsync (GraphQL) 禁用自省查询?
- command-line-interface - ThemeKit 主题标识标志未覆盖主题监视命令上的 config.yml
- scala - 如何在应用程序重启时维护 Alpakka/Akka Streams 源状态?