Yandex Cloud
Search
Contact UsGet started
  • Blog
  • Pricing
  • Documentation
  • All Services
  • System Status
    • Featured
    • Infrastructure & Network
    • Data Platform
    • Containers
    • Developer tools
    • Serverless
    • Security
    • Monitoring & Resources
    • ML & AI
    • Business tools
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Customer Stories
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Education and Science
    • Yandex Cloud Partner program
  • Blog
  • Pricing
  • Documentation
© 2025 Direct Cursus Technology L.L.C.
Tutorials
    • All tutorials
    • Basic internet service architecture and protection
    • Cost analysis by resource using Object Storage
      • Configuring a fault-tolerant architecture in Yandex Cloud
      • Integrating an L7 load balancer with Cloud CDN and Object Storage
      • Autoscaling an instance group to process messages enqueued in Message Queue
      • Updating an instance group under load
      • Creating a budget trigger that invokes a function to stop a VM
      • Deploying a fault-tolerant architecture with preemptible VMs
      • Creating triggers that invoke a function to stop a VM and send a Telegram notification

In this article:

  • Getting started
  • Required paid resources
  • Prepare the environment
  • Create a secret
  • Prepare a ZIP archive with the function code
  • Create a function
  • Create a trigger
  • Test the function
  • How to delete the resources you created
  1. Basic infrastructure
  2. Fault tolerance and scaling
  3. Deploying a fault-tolerant architecture with preemptible VMs

Deploying a fault-tolerant architecture with preemptible VMs

Written by
Yandex Cloud
Updated at May 7, 2025
  • Getting started
    • Required paid resources
  • Prepare the environment
  • Create a secret
  • Prepare a ZIP archive with the function code
  • Create a function
  • Create a trigger
  • Test the function
  • How to delete the resources you created

In this tutorial, you will create a scheduled Yandex Cloud Functions function in Node.js that will start a preemptible Yandex Compute Cloud VM if it was stopped.

The architecture we use here is suitable for VMs with non-critical loads. It allows you to reduce expenses by using preemptible VMs and, in case a VM goes down, ensures that idle time is no more than 60 seconds.

To deploy a fault-tolerant architecture with a preemptible VM:

  1. Set up your environment.
  2. Prepare a ZIP archive with the function code.
  3. Create a function.
  4. Create a trigger.
  5. Test the function.

If you no longer need the resources you created, delete them.

Getting startedGetting started

Sign up in Yandex Cloud and create a billing account:

  1. Navigate to the management console and log in to Yandex Cloud or register a new account.
  2. On the Yandex Cloud Billing page, make sure you have a billing account linked and it has the ACTIVE or TRIAL_ACTIVE status. If you do not have a billing account, create one and link a cloud to it.

If you have an active billing account, you can navigate to the cloud page to create or select a folder for your infrastructure to operate in.

Learn more about clouds and folders.

Required paid resourcesRequired paid resources

The infrastructure support costs include:

  • Fee for VM computing resources (see Compute Cloud pricing).
  • Fee for VM disks (see Compute Cloud pricing).
  • Fee for using a dynamic or static public IP address (see Yandex Virtual Private Cloud pricing).
  • Secret storage and request fees (see Yandex Lockbox pricing).
  • Fee for the number of function calls, computing resources allocated to the function, and outbound traffic (see Cloud Functions pricing).
  • Fee for logging operations and data storage in a log group (see Yandex Cloud Logging pricing) when using Cloud Logging.

Prepare the environmentPrepare the environment

  1. Create a service account for calling the function and assign the functions.functionInvoker and lockbox.payloadViewer roles to it.
  2. Create a preemptible VM.

Create a secretCreate a secret

Create a Yandex Lockbox secret where you will keep an OAuth token.

Note

Use an OAuth token if you cannot request an IAM token automatically. An IAM token gets updates more frequently and is therefore more secure.

Management console
CLI
Terraform
API
  1. In the management console, select the folder where you want to create a secret.
  2. From the list of services, select Lockbox.
  3. Click Create secret.
  4. In the Name field, enter a name for the secret, e.g., oauth-token.
  5. In the Secret type field, select Custom.
  6. Under Version:
    • In the Key field, enter key_token.
    • In the Value field, enter the OAuth token value required for authorizing the function.
  7. Click Create.

If you do not have the Yandex Cloud CLI yet, install and initialize it.

The folder specified when creating the CLI profile is used by default. To change the default folder, use the yc config set folder-id <folder_ID> command. You can specify a different folder using the --folder-name or --folder-id parameter.

To create a secret, run this command:

yc lockbox secret create --name oauth-token \
  --payload "[{'key': 'key_token', 'text_value': '<OAuth_token>'}]"

Where text_value is the OAuth token value required to authorize the function.

Result:

done (1s)
id: e6qu9ik259lb********
folder_id: b1g9d2k0itu4********
...
  status: ACTIVE
  payload_entry_keys:
    - key_token
  1. In the configuration file, describe the secret parameters:

    resource "yandex_lockbox_secret" "oauth-token" {
      name = "oauth-token"
    }
    
    resource "yandex_lockbox_secret_version" "my_version" {
      secret_id = yandex_lockbox_secret.my_secret.id
      entries {
        key        = "key_token"
        text_value = "<OAuth token>"
      }
    }
    

    Where:

    • name: Secret name.
    • key: Secret key.
    • text_value: OAuth token value required to authorize the function.

    Note

    We recommend using yandex_lockbox_secret_version_hashed: it stores values in Terraform state in hashed format. We continue supporting yandex_lockbox_secret_version.

    For more information about yandex_lockbox_secret_version_hashed, see the relevant provider documentation.

    For more information about Terraform resource parameters, see the overview documents by Terraform:

    • yandex_lockbox_secret
    • yandex_lockbox_secret_version
  2. Make sure the configuration files are correct.

    1. In the command line, navigate to the directory where you created the configuration file.

    2. Run a check using this command:

      terraform plan
      

    If the configuration description is correct, the terminal will display a list of the resources being created and their parameters. If the configuration contains any errors, Terraform will point them out.

  3. Deploy the cloud resources.

    1. If the configuration does not contain any errors, run this command:

      terraform apply
      
    2. Confirm secret creation by typing yes in the terminal and pressing Enter.

To create a secret, use the create REST API method for the Secret resource or the SecretService/Create gRPC API call.

Prepare a ZIP archive with the function codePrepare a ZIP archive with the function code

  1. Save this code to a file named index.js:

    import { serviceClients, Session, cloudApi } from '@yandex-cloud/nodejs-sdk';
    
    const {
      compute: {
        instance_service: {
          ListInstancesRequest,
          GetInstanceRequest,
          StartInstanceRequest,
        },
        instance: {
          IpVersion,
        },
      },
    } = cloudApi;
    
    const FOLDER_ID = process.env.FOLDER_ID;
    const INSTANCE_ID = process.env.INSTANCE_ID;
    const OAUTHTOKEN = process.env.OAUTHTOKEN;
    
    export const handler = async function (event, context) {
      const session = new Session({ oauthToken: OAUTHTOKEN });
      const instanceClient = session.client(serviceClients.InstanceServiceClient);
      const list = await instanceClient.list(ListInstancesRequest.fromPartial({
        folderId: FOLDER_ID,
      }));
      const state = await instanceClient.get(GetInstanceRequest.fromPartial({
        instanceId: INSTANCE_ID,
      }));
    
      var status = state.status
    
      if (status == 4){
        const startcommand = await instanceClient.start(StartInstanceRequest.fromPartial({
          instanceId: INSTANCE_ID,
        }));
      }
    
      return {
        statusCode: 200,
        body: {
          status
        }
      };
    };
    
  2. Save this code to a file named package.json:

    {
      "name": "my-awesome-package",
      "version": "1.0.0",
      "type": "module",
      "dependencies": {
        "@yandex-cloud/nodejs-sdk": "latest"
      }
    }
    
  3. Add the index.js and package.json files into the function-js.zip archive.

Create a functionCreate a function

Management console
CLI
Terraform
API
  1. In the management console, select the folder where you want to create a function.
  2. From the list of services, select Cloud Functions.
  3. Create a function:
    1. Click Create function.
    2. In the window that opens, enter function-restart-vms as the function name.
    3. Click Create.
  4. Create a function version:
    1. Select the nodejs18 runtime environment, disable the Add files with code examples option, and click Continue.
    2. In the Method field, select ZIP archive.
    3. In the File field, click Attach file and select the function-js.zip archive you created earlier.
    4. Specify the entry point: index.handler.
    5. Under Parameters, specify:
      • Timeout: 3.
      • Memory: 128 MB.
      • Service account: Select the previously created service account with permissions to call the function.
      • Environment variables:
        • FOLDER_ID: ID of the folder where you want to start the stopped VMs.
        • INSTANCE_ID: ID of the VM you want to start at interruption.
      • Lockbox secrets:
        • In the Environment variable field, specify OAUTHTOKEN.
        • In the Secret ID field, select the oauth-token secret you created earlier.
        • In the Version ID field, select the secret version.
        • In the Secret key field, select key_token as the key name.
      • If you want to avoid logging and paying for Cloud Logging, disable logging by selecting Not specified in the Logging field under Destination.
    6. Click Save changes.
  1. Create a function named function-restart-vms:

    yc serverless function create --name function-restart-vms
    

    Result:

    id: d4ebrmenrr7l********
    folder_id: b1g9d2k0itu4********
    created_at: "2023-10-28T17:26:58.200799757Z"
    name: function-restart-vms
    http_invoke_url: https://functions.yandexcloud.net/d4ebrmenrr7l********
    status: ACTIVE
    
  2. Create a version of the function-restart-vms function:

    yc serverless function version create \
      --function-name function-restart-vms \
      --memory=128m \
      --execution-timeout=3s \
      --runtime=nodejs18 \
      --entrypoint=index.handler \
      --service-account-id=<service_account_ID> \
      --environment FOLDER_ID=<folder_ID>,INSTANCE_ID=<VM_ID> \
      --secret name=oauth-token,version-id=<secret_version_ID>,key=key_token,environment-variable=OAUTHTOKEN \
      --source-path=./function-js.zip \
      --no-logging
    

    Where:

    • --function-name: Name of the function whose version you are creating.
    • --memory: Amount of RAM.
    • --execution-timeout: Maximum running time of the function until timeout.
    • --runtime: Runtime environment.
    • --entrypoint: Entry point.
    • --service-account-id: ID of the service account with permissions to call the function.
    • --environment: Environment variables:
      • FOLDER_ID: ID of the folder where you want to start the stopped VMs.
      • INSTANCE_ID: ID of the VM you want to start at interruption.
    • --secret: Yandex Lockbox secret data:
      • name: Secret name.
      • version-id: Secret version ID.
      • key: Secret key.
      • environment-variable: Environment variable where you will keep the secret.
    • --source-path: Path to the function-js.zip archive you created earlier.
    • Optionally, set the --no-logging flag to avoid logging and paying for Cloud Logging.

    Result:

    done (16s)
    id: d4etv5f4sjet********
    function_id: d4ebrmenrr7l********
    ...
    log_options:
      disabled: true
      folder_id: b1g9d2k0itu4********
    

If you do not have Terraform yet, install it and configure Yandex Cloud.

  1. In the configuration file, describe the function-restart-vms parameters and versions:

    resource "yandex_function" "function-restart-vms" {
      name               = "function-restart-vms"
      user_hash          = "first function"
      runtime            = "nodejs18"
      entrypoint         = "index.handler"
      memory             = "128"
      execution_timeout  = "3"
      service_account_id = "<service_account_ID>"
      folder_id = "<folder_ID>"
      environment = {
        FOLDER_ID = "<folder_ID>"
        INSTANCE_ID = "<VM_ID>"
      }
      secrets {
        id = "<secret_ID>"
        version_id = "<secret_version_ID>"
        key = "key_token"
        environment_variable = "OAUTHTOKEN"
      }
      content {
        zip_filename = "./function-js.zip"
      }
    }
    

    Where:

    • name: Function name.
    • user_hash: Random string to identify the function version.
    • runtime: Function runtime environment.
    • entrypoint: Entry point.
    • memory: Amount of memory allocated for the function, in MB.
    • execution_timeout: Function execution timeout.
    • service_account_id: ID of the service account with permissions to call the function.
    • folder_id: ID of the folder where you are creating the function.
    • environment: Environment variables:
      • FOLDER_ID: ID of the folder where you want to start the stopped VMs.
      • INSTANCE_ID: ID of the VM you want to start at interruption.
    • secrets: Yandex Lockbox secret data:
      • id: Secret ID.
      • version_id: Secret version ID.
      • key: Secret key.
      • environment_variable: Environment variable where you will keep the secret.
    • zip_filename: Path to the function-js.zip archive you created earlier.

    For more information about the yandex_function resource parameters, see this Terraform article.

  2. Make sure the configuration files are correct.

    1. In the command line, navigate to the directory where you created the configuration file.

    2. Run a check using this command:

      terraform plan
      

    If the configuration description is correct, the terminal will display a list of the resources you created and their parameters. If the configuration contains any errors, Terraform will point them out.

  3. Deploy the cloud resources.

    1. If the configuration does not contain any errors, run this command:

      terraform apply
      
    2. Confirm creating the function by typing yes in the terminal and pressing Enter.

      This will create a function named function-restart-vms in the specified folder. You can check the new resources and their settings using the management console or this CLI command:

      yc serverless function get function-restart-vms
      

      Result:

      id: d4ees84gsdsd********
      folder_id: b1g9d2k0itu4********
      created_at: "2023-08-09T10:11:40.740Z"
      name: function-restart-vms
      log_group_id: ckgjitlio5aj********
      http_invoke_url: https://functions.yandexcloud.net/d4ees84gsdsd********
      status: ACTIVE
      

To create a function, use the create REST API method for the Function resource or the FunctionService/Create gRPC API call.

To create a function version, use the createVersion REST API method for the Function resource or the FunctionService/CreateVersion gRPC API call.

Create a triggerCreate a trigger

Note

The trigger is initiated within 5 minutes of being created.

Management console
CLI
Terraform
API
  1. In the management console, select the folder where you want to create a trigger.
  2. From the list of services, select Cloud Functions.
  3. In the left-hand panel, select Triggers.
  4. Click Create trigger.
  5. Under Basic settings:
    • Enter a name for the trigger: timer.
    • In the Type field, select Timer.
    • In the Launched resource field, select Function.
  6. Under Timer settings, enter * * ? * * * or select Every minute.
  7. Under Function settings, select function-restart-vms and specify the following:
    • Function version tag: $latest.
    • Service account you created earlier with permissions to call the function.
  8. Click Create trigger.

To create a trigger that calls a function, run this command:

yc serverless trigger create timer \
  --name timer \
  --cron-expression '* * ? * * *' \
  --invoke-function-name function-restart-vms \
  --invoke-function-service-account-id <service_account_ID>

Where:

  • --name: Trigger name.
  • --cron-expression: Function call schedule specified as a cron expression.
  • --invoke-function-name: Name of the function to call.
  • --invoke-function-service-account-id: ID of the service account with permissions to call the function.

Result:

id: a1sv54ekvknb********
folder_id: b1g9d2k0itu4********
created_at: "2023-08-08T19:46:22.860681482Z"
...
      function_tag: $latest
      service_account_id: ajeh2dukocg3********
status: ACTIVE

To create a trigger that launches a function:

  1. In the configuration file, describe the timer trigger parameters:

    resource "yandex_function_trigger" "timer" {
      name        = "timer"
      timer {
        cron_expression = "* * ? * * *"
      }
      function {
        id = "<function_ID>"
        service_account_id = "<service_account_ID>"
      }
    }
    

    Where:

    • name: Trigger name.
    • cron_expression: Function call schedule specified as a cron expression.
    • id: ID of the function for the trigger to call.
    • service_account_id: ID of the service account with permissions to call the function.

    For more information about resource parameters in Terraform, see thisTerraform article.

  2. Make sure the configuration files are correct.

    1. In the command line, navigate to the directory where you created the configuration file.

    2. Run a check using this command:

      terraform plan
      

    If the configuration description is correct, the terminal will display a list of the resources you created and their parameters. If the configuration contains any errors, Terraform will point them out.

  3. Deploy the cloud resources.

    1. If the configuration does not contain any errors, run this command:

      terraform apply
      
    2. Confirm resource creation by typing yes in the terminal and pressing Enter.

      This will create a trigger named timer in the specified folder. You can check the new resources and their settings using the management console or this CLI command:

      yc serverless trigger get timer
      

      Result:

      id: a1s4bvdvmod0********
      folder_id: b1g9d2k0itu4********
      created_at: "2023-08-09T10:19:12.356Z"
      ...
            function_id: d4ebrmenrr7l********
            service_account_id: ajeh2dukocg3********
      status: ACTIVE
      

To create a timer, use the create REST API method for the Trigger resource or the TriggerService/Create gRPC API call.

Test the functionTest the function

Management console
  1. In the management console, navigate to the folder where you created your preemptible VM.
  2. From the list of services, select Compute Cloud.
  3. In the left-hand panel, select Virtual machines.
  4. Click next to the VM name and select Stop.
  5. In the window that opens, click Stop. The VM status will change to Stopped.
  6. Check the VM status in about one minute or later. The VM status should now be Running.

How to delete the resources you createdHow to delete the resources you created

To stop paying for the resources you created:

  1. Delete the trigger.
  2. Delete the function.
  3. Delete the secret.
  4. Delete the VM.
  5. If you logged data to a log group, delete it.

Was the article helpful?

Previous
Creating a budget trigger that invokes a function to stop a VM
Next
Creating triggers that invoke a function to stop a VM and send a Telegram notification
© 2025 Direct Cursus Technology L.L.C.