UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【GO】Cloud Function でAppEngineのインスタンスを止めたい

Cloud Function でAppEngineのインスタンスを止めたい

手順を調べたのでそのメモ

まずはgolang用のappengineモジュールのインポートを行う

import (
    "google.golang.org/api/appengine/v1"
)

インポートをしたらAppEngineクライアントのインスタンスを生成する

appengineService, err := appengine.NewService(ctx)

インスタンスの停止は以下の関数を使う

func (r *AppsServicesVersionsInstancesService) Delete(appsId string, servicesId string, versionsId string, instancesId string) *AppsServicesVersionsInstancesDeleteCall
Delete: Stops a running instance.The instance might be automatically recreated based on the scaling settings of the version. For more information, see "How Instances are Managed" (standard environment (https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed) | flexible environment (https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)).To ensure that instances are not re-created and avoid getting billed, you can stop all instances within the target version by changing the serving status of the version to STOPPED with the apps.services.versions.patch (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch) method.

- appsId: Part of `name`. Name of the resource requested. Example:

apps/myapp/services/default/versions/v1/instances/instance-1.
- instancesId: Part of `name`. See documentation of `appsId`. - servicesId: Part of `name`. See documentation of `appsId`. - versionsId: Part of `name`. See documentation of `appsId`.

次のようにしてAppsServicesVersionsInstancesServiceインスタンスを生成してDeleteを実行する

instancesService := appengine.NewAppsServicesVersionsInstancesService(appengineService)
instancesListCall := instancesService.List("appId", "serviceIdr", version)
instances, err := instancesListCall.Do()
ope, err := instancesService.Delete("appId", "serviceId", version, instances.Instances[0].Id).Do()

これを実行するときに必要な引数のうち、versionをみつけるためにList関数をつかう

https://pkg.go.dev/google.golang.org/api/appengine/v1#AppsServicesVersionsService.List

appsServicesVersionsService := appengine.NewAppsServicesVersionsService(appengineService)
versionsListCall := appsServicesVersionsService.List("appId", "serviceId")
versions, err := versionsListCall.Do()

これでバージョンリストがとれるので、必要なバージョンを使う