0

I want to schedule my SQL Instance of GCP. How to Trigger start/ stop SQL Instance automatically?

I already successfully scheduled the compute Engine VM but stuck in SQL Instance scheduling.

  • Does this answer your question? [How to run Google Cloud SQL only when I need it?](https://stackoverflow.com/questions/49547016/how-to-run-google-cloud-sql-only-when-i-need-it) – bsplosion Jul 15 '21 at 12:24

1 Answers1

2

In order to achieve this you can use a Cloud Function to make a call to the Cloud SQL Admin API to start and stop your Cloud SQL instance (you will need 2 Cloud functions)

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

You can see my code on how to use a Cloud Function to start a Cloud SQL instance and stop a Cloud SQL instance

After creating your Cloud Function you can configure the Cloud Scheduler to trigger the HTTP address of each Cloud function or you can follow the recommended approach of this guide and trigger the functions with pub/sub

Chris32
  • 4,716
  • 2
  • 18
  • 30
  • Hi thanks for your answer, Im getting this error trying your solution: "HttpError 400 when requesting... Invalid request: Only custom machine instance type and shared-core instance type allowed for PostgreSQL database." – norbertoonline Feb 02 '21 at 16:32