Yandex Cloud
Search
Contact UsGet started
  • Pricing
  • Customer Stories
  • Documentation
  • Blog
  • All Services
  • System Status
    • Featured
    • Infrastructure & Network
    • Data Platform
    • Containers
    • Developer tools
    • Serverless
    • Security
    • Monitoring & Resources
    • AI for business
    • Business tools
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Center for Technologies and Society
    • Yandex Cloud Partner program
  • Pricing
  • Customer Stories
  • Documentation
  • Blog
© 2025 Direct Cursus Technology L.L.C.
Tutorials
    • All tutorials
    • Architecture and protection of a basic web service
    • 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
        • Overview
        • Management console, CLI, and API
        • Terraform
      • 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:

  • Get your cloud ready
  • Required paid resources
  • Create an infrastructure
  • Test instance group scaling
  • How to delete the resources you created
  1. Basic infrastructure
  2. Fault tolerance and scaling
  3. Scheduled instance group scaling
  4. Terraform

Scheduled scaling of VM groups using Terraform

Written by
Yandex Cloud
Updated at August 14, 2025
  • Get your cloud ready
    • Required paid resources
  • Create an infrastructure
  • Test instance group scaling
  • How to delete the resources you created

To set up scheduled scaling for a VM group using Terraform:

  1. Get your cloud ready.
  2. Create your infrastructure.
  3. Test your instance group scaling.

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

Get your cloud readyGet your cloud ready

Sign up for Yandex Cloud and create a billing account:

  1. Navigate to the management console and log in to Yandex Cloud or create 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.

Learn more about clouds and folders here.

Required paid resourcesRequired paid resources

The infrastructure support costs include:

  • Fee for disks and continuously running VMs (see Compute Cloud pricing).
  • Function calls, computing resources allocated to executing the function, and outgoing traffic (see Cloud Functions pricing).

Create an infrastructureCreate an infrastructure

With Terraform, you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.

Terraform is distributed under the Business Source License. The Yandex Cloud provider for Terraform is distributed under the MPL-2.0 license.

For more information about the provider resources, see the relevant documentation on the Terraform website or its mirror.

Create an infrastructure with Terraform:

  1. Install Terraform and specify the Yandex Cloud provider installation source (see Configure your provider, step 1).

  2. Prepare your infrastructure description files:

    Ready-made configuration
    Manually
    1. Clone the repository with configuration files.

      git clone https://github.com/yandex-cloud-examples/yc-vm-group-scheduled-scaling
      
    2. Navigate to the repository directory. Make sure it contains the following files:

      • vm-scale-scheduled.tf: New infrastructure configuration.
      • vm-scale-scheduled.auto.tfvars: User data file.
      • vm-scale-scheduled-function.zip: Cloud Functions function code archive.
    1. Create a folder.

    2. In this folder, create:

      • vm-scale-scheduled.tf: New infrastructure configuration file:

        vm-scale-scheduled.tf
        # Declaring variables for confidential parameters
        
        variable "folder_id" {
          type = string
        }
        
        variable "username" {
          type = string
        }
        
        variable "ssh_key_path" {
          type = string
        }
        
        # Configuring a provider
        
        terraform {
          required_providers {
            yandex = {
              source  = "yandex-cloud/yandex"
              version = ">= 0.47.0"
            }
          }
        }
        
        provider "yandex" {
          folder_id = var.folder_id
        }
        
        # Creating a service account and assigning roles to it
        
        resource "yandex_iam_service_account" "vm-scale-scheduled-sa" {
          name      = "vm-scale-scheduled-sa"
        }
        
        resource "yandex_resourcemanager_folder_iam_member" "vm-scale-scheduled-sa-role-compute" {
          folder_id = var.folder_id
          role      = "compute.editor"
          member    = "serviceAccount:${yandex_iam_service_account.vm-scale-scheduled-sa.id}"
        }
        
        resource "yandex_resourcemanager_folder_iam_member" "vm-scale-scheduled-sa-role-iam" {
          folder_id = var.folder_id
          role      = "iam.serviceAccounts.user"
          member    = "serviceAccount:${yandex_iam_service_account.vm-scale-scheduled-sa.id}"
        }
        
        resource "yandex_resourcemanager_folder_iam_member" "vm-scale-scheduled-sa-role-functions" {
          folder_id = var.folder_id
          role      = "functions.functionInvoker"
          member    = "serviceAccount:${yandex_iam_service_account.vm-scale-scheduled-sa.id}"
        }
        
        # Creating a cloud network and subnets
        
        resource "yandex_vpc_network" "vm-scale-scheduled-network" {
          name = "vm-scale-scheduled-network"
        }
        
        resource "yandex_vpc_subnet" "vm-scale-scheduled-subnet-a" {
          name           = "vm-scale-scheduled-subnet-a"
          zone           = "ru-central1-a"
          v4_cidr_blocks = ["192.168.1.0/24"]
          network_id     = yandex_vpc_network.vm-scale-scheduled-network.id
        }
        
        resource "yandex_vpc_subnet" "vm-scale-scheduled-subnet-b" {
          name           = "vm-scale-scheduled-subnet-b"
          zone           = "ru-central1-b"
          v4_cidr_blocks = ["192.168.2.0/24"]
          network_id     = yandex_vpc_network.vm-scale-scheduled-network.id
        }
        
        # Creating an image
        
        resource "yandex_compute_image" "vm-scale-scheduled-image" {
          source_family = "ubuntu-2004-lts"
        }
        
        # Creating an instance group
        
        resource "yandex_compute_instance_group" "vm-scale-scheduled-ig" {
          name               = "vm-scale-scheduled-ig"
          service_account_id = yandex_iam_service_account.vm-scale-scheduled-sa.id
        
          allocation_policy {
            zones = [
              "ru-central1-a",
              "ru-central1-b"
            ]
          }
        
          instance_template {
            boot_disk {
              mode = "READ_WRITE"
              initialize_params {
                image_id = yandex_compute_image.vm-scale-scheduled-image.id
                size     = 15
              }
            }
        
            platform_id = "standard-v3"
            resources {
              cores         = 2
              core_fraction = 20
              memory        = 2
            }
        
            network_interface {
              network_id = yandex_vpc_network.vm-scale-scheduled-network.id
              subnet_ids = [
                yandex_vpc_subnet.vm-scale-scheduled-subnet-a.id,
                yandex_vpc_subnet.vm-scale-scheduled-subnet-b.id
              ]
            }
        
            metadata = {
              user-data = "#cloud-config\nusers:\n  - name: ${var.username}\n    groups: sudo\n    shell: /bin/bash\n    sudo: 'ALL=(ALL) NOPASSWD:ALL'\n    ssh_authorized_keys:\n      - ${file("${var.ssh_key_path}")}"
            }
          }
        
          scale_policy {
            fixed_scale {
              size = 2
            }
          }
        
          deploy_policy {
            max_unavailable = 2
            max_creating    = 2
            max_expansion   = 2
            max_deleting    = 2
          }
        
          depends_on = [
            yandex_resourcemanager_folder_iam_member.vm-scale-scheduled-sa-role-compute,
            yandex_resourcemanager_folder_iam_member.vm-scale-scheduled-sa-role-iam
          ]
        }
        
        # Creating a function
        
        resource "yandex_function" "vm-scale-scheduled-function" {
          name               = "vm-scale-scheduled-function"
          runtime            = "bash"
        
          user_hash          = "function-v1"
          entrypoint         = "handler.sh"
          content {
            zip_filename = "vm-scale-scheduled-function.zip"
          }
        
          execution_timeout  = "60"
          memory             = "128"
          service_account_id = yandex_iam_service_account.vm-scale-scheduled-sa.id
        
          environment = {
            IG_NAME      = yandex_compute_instance_group.vm-scale-scheduled-ig.name
            IG_BASE_SIZE = "2"
            FOLDER_ID    = var.folder_id
          }
        
          depends_on = [
            yandex_resourcemanager_folder_iam_member.vm-scale-scheduled-sa-role-functions
          ]
        }
        
        # Creating a trigger
        
        resource "yandex_function_trigger" "vm-scale-scheduled-trigger" {
          name = "vm-scale-scheduled-trigger"
          timer {
            cron_expression = "*/2 * * * ? *"
          }
          function {
            id                 = yandex_function.vm-scale-scheduled-function.id
            tag                = "$latest"
            service_account_id = yandex_iam_service_account.vm-scale-scheduled-sa.id
          }
        
          depends_on = [
            yandex_resourcemanager_folder_iam_member.vm-scale-scheduled-sa-role-functions
          ]
        }
        
      • vm-scale-scheduled.auto.tfvars: User data file:

        vm-scale-scheduled.auto.tfvars
        folder_id    = "<folder_ID>"
        username     = "<VM_username>"
        ssh_key_path = "<path_to_public_SSH_key>"
        
      • handler.sh file with the Cloud Functions function code:

        handler.sh

        Warning

        If you are creating a file in Windows, make sure that newline characters are in \n Unix format rather than \r\n. You can replace line breaks in a text editor, such as Notepad++, or with such tools as dos2unix or Tofrodos.

        # Get ID and current size of the instance group
        IG_SPEC=$(yc compute instance-group get --name $IG_NAME --folder-id $FOLDER_ID --format json)
        IG_ID=$(jq -r ".id" <<< $IG_SPEC)
        IG_SIZE=$(jq -r ".scale_policy.fixed_scale.size" <<< $IG_SPEC)
        
        # Calculate new size for the instance group
        if [ $IG_SIZE = $IG_BASE_SIZE ]; then
            IG_SIZE="$(($IG_BASE_SIZE + 1))"
        else
            IG_SIZE=$IG_BASE_SIZE
        fi
        
        # Update the instance group
        yc compute instance-group update --id $IG_ID --scale-policy-fixed-scale-size $IG_SIZE
        
    3. In the same folder, create the vm-scale-scheduled-function.zip archive with handler.sh.

    For more information about the properties of Terraform resources, see the relevant Terraform guides:

    • Service account: yandex_iam_service_account.
    • Network: yandex_vpc_network.
    • Subnets: yandex_vpc_subnet.
    • VM image: yandex_compute_image.
    • VM group: yandex_compute_instance_group.
    • Function: yandex_function.
    • Trigger: yandex_function_trigger.
  3. In the vm-scale-scheduled.auto.tfvars file, set the following user-defined properties:

    • folder_id: Resource folder ID.
    • username: VM user name.
    • ssh_key_path: Path to the public SSH key required to authenticate the user on the VM. You can create a key pair by following this guide.
  4. Create the resources:

    1. In the terminal, go to the directory where you edited the configuration file.

    2. Make sure the configuration file is correct using this command:

      terraform validate
      

      If the configuration is correct, you will get this message:

      Success! The configuration is valid.
      
    3. Run this command:

      terraform plan
      

      You will see a detailed list of resources. No changes will be made at this step. If the configuration contains any errors, Terraform will show them.

    4. Apply the changes:

      terraform apply
      
    5. Type yes and press Enter to confirm the changes.

Once you created the infrastructure, test your instance group scaling.

Test instance group scalingTest instance group scaling

Management console
CLI
API
  1. In the management console, select example-folder.
  2. From the list of services, select Compute Cloud.
  3. In the left-hand panel, select Instance groups.
  4. Select vm-scale-scheduled-ig.
  5. Under VM states, make sure the number of instances changes every two minutes: increases from 2 to 3, then decreases from 3 to 2, etc. You can also check if the instance group has been updated by opening the Operations tab.

Run the following command several times:

yc compute instance-group get vm-scale-scheduled-ig \
  --folder-name example-folder

Result:

id: cl1l0ljqbmkp********
folder_id: b1g9hv2loamq********
created_at: "2022-03-28T13:24:20.693Z"
...
managed_instances_state:
  target_size: "2"
  running_actual_count: "2"
...

The value of the target_size field for the group should change from 2 to 3 and back.

Get information about the vm-scale-scheduled-ig instance group multiple times using the get REST API method for the InstanceGroup resource or the InstanceGroupService/Get gRPC API call. The value of the target_size field for the group should change from 2 to 3 and back.

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

To stop paying for the resources you created:

  1. Open the vm-scale-scheduled.tf configuration file and delete your infrastructure description from it.

  2. Apply the changes:

    1. In the terminal, go to the directory where you edited the configuration file.

    2. Make sure the configuration file is correct using this command:

      terraform validate
      

      If the configuration is correct, you will get this message:

      Success! The configuration is valid.
      
    3. Run this command:

      terraform plan
      

      You will see a detailed list of resources. No changes will be made at this step. If the configuration contains any errors, Terraform will show them.

    4. Apply the changes:

      terraform apply
      
    5. Type yes and press Enter to confirm the changes.

See alsoSee also

  • Scheduled scaling of instance groups using the management console, CLI, and API

Was the article helpful?

Previous
Management console, CLI, and API
Next
Autoscaling an instance group to process messages enqueued in Message Queue
© 2025 Direct Cursus Technology L.L.C.