Cloud SQL instance is not being stopped using Cloud Schedule after these steps:
- Create a pub/sub topic that is supposed to trigger the cloud function.
- Deploy a cloud function using the topic already created in step 1, with the below python (3.8) code file and requirements. (Entry point:
start_stop) - Create a cloud scheduler job to trigger the cloud function on a regular basis with the topic created in step 1.
The payload is set to
start [CloudSQL instance name]orstop [CloudSQL instance name]to start or stop the specified instance
Main.py:
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
import base64
from pprint import pprint
credentials = GoogleCredentials.get_application_default()
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials, cache_discovery=False)
project = 'projectID'
def start_stop(event, context):
print(event)
pubsub_message = base64.b64decode(event['data']).decode('utf-8')
print(pubsub_message)
command, instance_name = pubsub_message.split(' ', 1)
if command == 'start':
start(instance_name)
elif command == 'stop':
stop(instance_name)
else:
print("unknown command " + command)
def start(instance_name):
print("starting " + instance_name)
patch(instance_name, "ALWAYS")
def stop(instance_name):
print("stopping " + instance_name)
patch(instance_name, "NEVER")
def patch(instance, activation_policy):
request = service.instances().get(project=project, instance=instance)
response = request.execute()
j = response["settings"]
settingsVersion = int(j["settingsVersion"])
dbinstancebody = {
"settings": {
"settingsVersion": settingsVersion,
"activationPolicy": activation_policy
}
}
dbinstancebody = {
"settings": {
"settingsVersion": response["settings"]["settingsVersion"],
"activationPolicy": activation_policy
}
}
request = service.instances().update(
project=project,
instance=instance,
body=dbinstancebody)
response = request.execute()
pprint(response)
Requirements.txt
google-api-python-client==1.10.0
google-auth-httplib2==0.0.4
google-auth==1.21.1
oauth2client==4.1.3
When I click RUN NOW button in the stop scheduler, it's executed successfully, but when I navigate to SQL instance, it is not stopped.
Can someone spot what I am missing? If you need more details, just let me know please, I have just started with GCP. :)