Cloud Scheduler to stop a Cloud SQL database

Опубликовано: 16 Март 2026
на канале: mkdev
1,243
21

In this video Pablo Inigo will show how to stop and start a Cloud SQL database in a daily basis with a Cloud Scheduler calling a Pub/Sub Topic, calling a Step Function. MAGIC!!!!

If you or your company need consulting and training around infrastructure as code and infrastructure automation topics, reach out to us via email - [email protected] or check out our website: https://mkdev.me/en/b

#GCP #googlecloud #cloudscheduler #cloudfunctions #cloudsq #pub/sub #pubsub #databases


package p

import (
"context"
"encoding/json"
"log"

"golang.org/x/oauth2/google"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)

type PubSubMessage struct {
Data []byte `json:"data"`
}

type MessagePayload struct {
Instance string
Project string
Action string
}

func ProcessPubSub(ctx context.Context, m PubSubMessage) error {
var psData MessagePayload
err := json.Unmarshal(m.Data, &psData)
if err != nil {
log.Println(err)
}
log.Printf("Request received for Cloud SQL instance %s action: %s, %s", psData.Action, psData.Instance, psData.Project)

hc, err := google.DefaultClient(ctx, sqladmin.CloudPlatformScope)
if err != nil {
return err
}

service, err := sqladmin.New(hc)
if err != nil {
return err
}

action := "UNDEFINED"
switch psData.Action {
case "start":
action = "ALWAYS"
case "stop":
action = "NEVER"
default:
log.Fatal("No valid action provided.")
}

// See more examples at:
// https://cloud.google.com/sql/docs/sql...
rb := &sqladmin.DatabaseInstance{
Settings: &sqladmin.Settings{
ActivationPolicy: action,
},
}

resp, err := service.Instances.Patch(psData.Project, psData.Instance, rb).Context(ctx).Do()
if err != nil {
log.Fatal(err)
}
log.Printf("%#v\n", resp)
return nil
}