使用Cloud Functions启动/停止Google Cloud SQL实例

时间:2020-01-26 09:13:55

标签: google-cloud-platform google-cloud-functions

我是Google Cloud Platform的新手。我正在寻找在预定义的时间自动启动和停止mySQL实例的方法。 我发现我们可以创建一个云功能来启动/停止实例,然后使用云调度程序来触发它。但是,我无法理解其工作原理。

我使用了在GitHub中找到的代码。 https://github.com/chris32g/Google-Cloud-Support/blob/master/Cloud%20Functions/turn_on_cloudSQL_instance https://github.com/chris32g/Google-Cloud-Support/blob/master/Cloud%20Functions/turn_off_CloudSQL_instance

但是,我对诸如node,python或go之类的任何编程语言都不熟悉。这就是造成混乱的原因。以下是我在GitHub上找到的打开Cloud SQL实例的代码:

# This file uses the Cloud SQL API to turn on a Cloud SQL instance.
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials)
project = 'wave24-gonchristian'  # TODO: Update placeholder value.


def hello_world(request):

    instance = 'test'  # TODO: Update placeholder value.
    request = service.instances().get(project=project, instance=instance)
    response = request.execute()
    j = response["settings"]
    settingsVersion = int(j["settingsVersion"])

    dbinstancebody = {
       "settings": {
           "settingsVersion": settingsVersion,
           "tier": "db-n1-standard-1",
           "activationPolicy": "Always"
       }
    }

    request = service.instances().update(
       project=project,
       instance=instance,
       body=dbinstancebody)
    response = request.execute()
# pprint(response)

    request_json = request.get_json()

    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return f"Hello World!"

________________________

requirements.txt

google-api-python-client==1.7.8
google-auth-httplib2==0.0.3
google-auth==1.6.2
oauth2client==4.1.3

正如我之前提到的,我对Python不熟悉。我刚刚在GitHub上找到了这段代码。我试图了解此特定部分的作用:

dbinstancebody = {
       "settings": {
           "settingsVersion": settingsVersion,
           "tier": "db-n1-standard-1",
           "activationPolicy": "Always"
       }
}

3 个答案:

答案 0 :(得分:1)

dbinstancebody = {
       "settings": {
           "settingsVersion": settingsVersion,
           "tier": "db-n1-standard-1",
           "activationPolicy": "Always"
       }
}

您要更新的specifies sql instance properties上方的代码块,其中与您的案例最相关的是activationPolicy,它允许您停止/启动sql实例。

对于第二代实例,激活策略仅用于启动或停止实例。您可以通过启动和停止实例来更改激活策略。停止实例可防止进一步收取实例费用。

激活策略可以具有两个值Always或Never。始终将启动实例,从不将停止实例。

答案 1 :(得分:0)

您可以使用 API 将 activationPolicy 修改为 "NEVER" 以停止服务器或将 "ALWAYS" 修改为启动它。

# PATCH
https://sqladmin.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}

# BODY
{
  "settings": {
    "activationPolicy": "NEVER"
  }
}

有关详细信息,请参阅 Cloud SQL 文档中的这篇文章:Starting, stopping, and restarting instances。您还可以尝试 REST API reference 中的 instances.patch 方法。

答案 2 :(得分:0)

请尝试以下代码:

from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
import os

credentials = GoogleCredentials.get_application_default()
service = discovery.build("sqladmin", "v1beta4", credentials=credentials)
project_id = os.environ.get("GCP_PROJECT")

# setup this vars using terraform and assign the value via terraform
desired_policy = os.environ.get("DESIRED_POLICY") # ALWAYS or NEVER
instance_name = os.environ.get("INSTANCE_NAME")

def cloudsql(request):
    request = service.instances().get(project=project_id, instance=instance_name)
    response = request.execute()

    state = response["state"]
    instance_state = str(state)

    x = response["settings"]
    current_policy = str(x["activationPolicy"])

    dbinstancebody = {"settings": {"activationPolicy": desired_policy}}


    if instance_state != "RUNNABLE":
        print("Instance is not in RUNNABLE STATE")
    else:
        if desired_policy != current_policy:
            request = service.instances().patch(
                project=project_id, instance=instance_name, body=dbinstancebody
            )
            response = request.execute()

            pprint(response)
        else:
            print(f"Instance is in RUNNABLE STATE but is also already configured with the desired policy: {desired_policy}")

在我的 repo 中,您可以获得有关如何使用 Terraform 设置云功能的更多信息。这个云函数的目的是做你想做的,但它使用了环境变量,如果你不想使用它们,只需更改python代码中的变量值即可。

这是我的存储库 Repo