我的项目有相同的用例,我使用这个 python 函数来启动和停止虚拟机,我的函数可以处理路径 start 和 stop
from flask import Flask, request, abort
import os
import logging
app = Flask(__name__)
@app.route('/')
@app.route('/<path:path>')
def power(path=None):
#this libraries are mandatory to reach compute engine api
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
#the function will take the service account of your function
credentials = GoogleCredentials.get_application_default()
#this line is to specify the api that we gonna use, in this case compute engine
service = discovery.build('compute', 'v1', credentials=credentials, cache_discovery=False)
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
# Project ID for this request.
project = yourprojectID # Update placeholder value.
zone = request.args.get('zone', None)
instance = request.args.get('instance', None)
#call the method to start or stop the instance
if (request.path == "/stop"):
req = service.instances().stop(project=project, zone=zone, instance=instance)
elif (request.path == "/start"):
req = service.instances().start(project=project, zone=zone, instance=instance)
else:
abort(418)
#execute the command
response = req.execute()
print(response)
return ("OK")
if __name__ == '__main__':
app.run(port=3000, debug=True)
requirements.txt 文件
google-api-python-client
oauth2client
flask
调度器配置
-
Create a service account 和 functions.invoker permission 在你的函数中
- Create new Cloud scheduler job
- 以 cron 格式指定频率。
- 将 HTTP 指定为目标类型。
- 一如既往地添加您的云函数和方法的 URL。
- 从 Auth 标头下拉列表中选择令牌 OIDC
- 在服务帐户文本框中添加服务帐户电子邮件。
-
audience field中只需要写函数的URL,不需要任何附加参数
在云调度程序上,我使用这些 URL 来实现我的功能
https://us-central1-yourprojectID.cloudfunctions.net/power/stop?zone=us-central1-a&instance=instance-1
https://us-central1-yourprojectID.cloudfunctions.net/power/stop?zone=us-central1-a&instance=instance-1
我使用了这些观众
https://us-central1-yourprojectID.cloudfunctions.net/power
请在代码和网址中替换yourprojectID
us-central1是我的函数所在的区域,power是我的函数的名称,us-central1-a是我的实例所在的区域,instance-1是我的实例的名称
Java 更新
Cloud 函数支持 java11 和 maven,但这是测试版
首先你需要这个依赖,请将以下几行添加到你的 pom.xml 文件中:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-compute</artifactId>
<version>beta-rev20200629-1.30.10</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.30.10</version>
</dependency>
启动虚拟机的云功能
package com.example;
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Operation;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
public class Example implements HttpFunction {
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception, IOException, GeneralSecurityException {
// Project ID for this request.
String project = "my-project"; // TODO: Update placeholder value.
// The name of the zone for this request.
String zone = "my-zone"; // TODO: Update placeholder value.
// Name of the instance resource to start.
String instance = "my-instance"; // TODO: Update placeholder value.
Compute computeService = createComputeService();
// you can change the method start to stop
Compute.Instances.Start request = computeService.instances().start(project, zone, instance);
Operation xresponse = xrequest.execute();
// TODO: Change code below to process the `response` object:
System.out.println(xresponse);
BufferedWriter writer = response.getWriter();
writer.write("Done");
}
public static Compute createComputeService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()) {
credential =
credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
}
return new Compute.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Google-ComputeSample/0.1")
.build();
}
}
有关更多信息,您可以查看此文档中的 document 是不同编程语言的一些示例