Hometutorials
manage instances with serverless framework

Jump toUpdate content

Managing compute Instances with the serverless framework

Reviewed on 25 January 2022Published on 21 December 2021
  • serverless
  • instances
  • python

In this tutorial you will discover some examples of Instance automation using Python and the serverless framework:

  • Automatically backup your instance
  • Automatically shut down / start instances
Requirements:

Automatically back up your Instance

For this example we will use Scaleway SDK and Scaleway console, for more information please refer to the Python SDK Documentation and the package your function and upload it as a zip-file page how to.

  1. Create a project using the serverless framework (in a terminal):

    serverless create --template-url https://github.com/scaleway/serverless-scaleway-functions/tree/master/examples/python3 --path myService
  2. Install the Scaleway SDK using pip:

    pip install scaleway-sdk --target ./package
  3. Navigate to the myService directory and edit the file handler.py in a text editor as follows. Then save the file and exit the editor.

    from scaleway.apis import ComputeAPI
    from datetime import date
    import os

    api = ComputeAPI(auth_token=os.environ['API_KEY'])
    snapshot_name=os.environ['SNAPSHOT_NAME']
    volume_id=os.environ['VOLUME_ID']
    project_id=os.environ['PROJECT_ID']

    def handle(event, context):
    snapshot_date = date.today().strftime("%Y%m%d%h%m")


    res=api.query().snapshots.post({"name": snapshot_date+"_"+snapshot_name,"volume_id": volume_id,"project": project_id})

    return {
    "body": res,
    "statusCode": 200,
    }
  4. Zip the handler.py and the package folder.

  5. In the Scaleway console:

  • Upload your zip file
  • Define the following environment variable
    • API_KEY: {Your API KEY}
    • PROJECT_ID: {Your project Id}
    • SNAPSHOT_NAME: {Name of the snapshot}
    • VOLUME_ID: {Volume to backup}
    • REGION: {Your Instance region}
  • Deploy your function
  1. (Optional) to ensure the functions works well you can call it and follow the logs

Automatically shut down / start Instances

For this example we will use the native python library urllib, which enables us to write the code directly into the Scaleway console. All information about the Instance API can be found in the developers documentation

Note:

You require your Instance information for the following steps.

  1. Create a function from the Scaleway console.

  2. Edit the file handler as follows:

    import os
    from urllib import request,parse,error
    import json

    auth_token=os.environ['X-AUTH-TOKEN']

    def handle(event, context):
    ## get information from cron
    event_body=eval(event["body"])
    zone=event_body["zone"]
    server_id=event_body["server_id"]
    action=event_body["action"] #action should be "poweron" or "poweroff"

    #create request
    url=f"https://api.scaleway.com/instance/v1/zones/{zone}/servers/{server_id}/action"
    data=json.dumps({"action":action}).encode('ascii')
    req = request.Request(url, data=data, method="POST")
    req.add_header('Content-Type', 'application/json')
    req.add_header('X-Auth-Token',auth_token)

    #Sending request to Instance API
    try:
    res=request.urlopen(req).read().decode()
    except error.HTTPError as e:
    res=e.read().decode()

    return {
    "body": json.loads(res),
    "statusCode": 200,
    }
  3. Add the environment variable X-AUTH-TOKEN.

  4. Create cron jobs dedicated to start or stop your Instance in the Advanced Section.

    • To stop an Instance:
    {
    "zone":"{ZONE}",
    "server_id":"{XXXXXXX-XXXX-XXX-XXXX-XXXXXXX}",
    "action":"poweroff"
    }
    • To start an Instance:
    {
    "zone":"{ZONE}",
    "server_id":"{XXXXXXX-XXXX-XXX-XXXX-XXXXXXX}",
    "action":"poweron"
    }