[Yandex Cloud documentation](../../../index.md) > [Yandex Cloud Backup](../../index.md) > [Tutorials](../index.md) > [Associating a backup policy with a VM automatically](index.md) > Terraform

# Associating a Yandex Cloud Backup policy with a VM automatically using Terraform

To create a virtual machine automatically associated with a Cloud Backup policy:

1. [Get your cloud ready](#before-begin).
1. [Activate Cloud Backup](#service-activate).
1. [Create your infrastructure](#deploy).

If you no longer need the resources you created, [delete them](#clear-out).

## Get your cloud ready {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../../billing/quickstart/index.md) and [link](../../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

The infrastructure support cost includes:

* Fee for VM computing resources (see [Yandex Compute Cloud pricing](../../../compute/pricing.md#prices-instance-resources)).
* Fee for VM disks (see [Yandex Compute Cloud pricing](../../../compute/pricing.md#prices-storage)).
* Fee for using a dynamic external IP address (see [Yandex Virtual Private Cloud pricing](../../../vpc/pricing.md#prices-public-ip)).
* Fee for VMs connected to Cloud Backup and the size of backups (see [Yandex Cloud Backup pricing](../../pricing.md#rules)).

## Activate Cloud Backup {#service-activate}

{% note info %}

To activate the service, you need _at least_ the `backup.user` [role](../../security/index.md#backup-user) for the [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) in which you want to create backups of VMs or BareMetal servers.

{% endnote %}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a VM connected to Cloud Backup.
  1. Navigate to **Cloud Backup**.
  1. If you have not activated Cloud Backup yet, click **Activate**.

      If there is no **Activate** button, and you can create a VM connected to Cloud Backup, it means the service has already been activated. Proceed to the next step.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).
  
  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.
  
  1. View the description of the [CLI](../../../cli/index.md) command to activate the service:
  
     ```bash
     yc backup provider activate --help
     ```
  
  1. Activate the service in the default folder:
  
     ```bash
     yc backup provider activate --async
     ```
  
     Where `--async` displays the operation progress info. This is an optional parameter.
  
  1. Once you execute the command, you will get the activation warning: `This command will activate backup provider for your folder. Do you confirm this action to be executed? [Yes/no][y/N]`. Confirm the activation by typing `yes` or `y` in the terminal.
  
     {% note tip %}
  
     Use the `--force` flag to activate the service without a confirmation.
  
     {% endnote %}
  
     Result:
  
     ```text
     id: cdgmnefxiatx********
     description: activate provider
     created_at: "2024-10-14T09:03:47.960564Z"
     created_by: ajec1gaqcmtr********
     modified_at: "2024-10-14T09:03:47.960564Z"
     done: true
     metadata:
       '@type': type.googleapis.com/yandex.cloud.backup.v1.ActivateProviderMetadata
       folder_id: b1go3el0d8fs********
     response:
       '@type': type.googleapis.com/google.protobuf.Empty
       value: {}
     ```
  
  After activation, the system automatically creates the following backup policies:
  * `Default daily`: Daily incremental backup with the last 15 backups retained.
  * `Default weekly`: Weekly incremental backup with the last 15 backups retained.
  * `Default monthly`: Monthly incremental backup with the last 15 backups retained.
  
  If you prefer not to create them, use the `--skip-default-policy` parameter.

{% endlist %}

## Create the infrastructure {#deploy}

{% note info %}

Associating a Yandex Cloud Backup policy with a VM is available for [Terraform provider](../../../terraform/index.md) `0.127.0` and higher.

{% endnote %}

With [Terraform](https://www.terraform.io/), 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](https://github.com/hashicorp/terraform/blob/main/LICENSE). The [Yandex Cloud provider for Terraform](https://github.com/yandex-cloud/terraform-provider-yandex) is distributed under the [MPL-2.0](https://www.mozilla.org/en-US/MPL/2.0/) license.

For more information about the provider resources, see the guides on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../../terraform/index.md).

To create an infrastructure using Terraform:

1. [Install Terraform](../../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform), [get the credentials](../../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials), and specify the source for installing the Yandex Cloud provider (see [Configure your provider](../../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider), Step 1).
1. Set up your infrastructure description files:

    {% list tabs group=infrastructure_description %}

    - Ready-made configuration {#ready}

      1. Clone the repository with configuration files.

          ```bash
          git clone https://github.com/yandex-cloud-examples/yc-baas-backup-policy-auto-binding
          ```

      1. Navigate to the repository directory. It should now contain the following files:

          * `backup-policy-auto-binding-config.tf`: New infrastructure configuration.
          * `cloud-init.yaml`: VM metadata file.

    - Manually {#manual}

      1. Create a folder for configuration files.
      1. In the folder, create:

          1. `backup-policy-auto-binding-config.tf` configuration file:

            {% cut "backup-policy-auto-binding-config.tf" %}

            ```hcl
            # Configuring the provider
            
            terraform {
              required_providers {
                yandex = {
                  source = "yandex-cloud/yandex"
                }
              }
              required_version = ">= 0.13"
            }
            
            provider "yandex" {
              zone = "ru-central1-a"
            }
            
            # Creating a service account
            
            resource "yandex_iam_service_account" "my_sa" {
              name = "backup-sa"
            }
            
            # Assigning roles to a service account
            
            resource "yandex_resourcemanager_folder_iam_member" "my_binding" {
              folder_id = yandex_iam_service_account.my_sa.folder_id
              role      = "backup.user"
              member    = "serviceAccount:${yandex_iam_service_account.my_sa.id}"
            }
            
            # Creating a cloud network
            
            resource "yandex_vpc_network" "my_backup_network" {
              name = "cloud-network"
            }
            
            # Creating a cloud subnet
            
            resource "yandex_vpc_subnet" "my_backup_subnet" {
              zone           = "ru-central1-a"
              network_id     = yandex_vpc_network.my_backup_network.id
              v4_cidr_blocks = ["192.168.0.0/24"]
            }
            
            # Creating a security group
            # https://yandex.cloud/ru/docs/backup/concepts/vm-connection#vm-network-access
            
            resource "yandex_vpc_security_group" "my_backup_security_group" {
              name       = "backup-sg"
              network_id = yandex_vpc_network.my_backup_network.id
              egress {
                protocol       = "TCP"
                from_port      = 7770
                to_port        = 7800
                v4_cidr_blocks = ["84.47.172.0/24"]
              }
              egress {
                protocol       = "TCP"
                port           = 443
                v4_cidr_blocks = ["213.180.204.0/24", "213.180.193.0/24", "178.176.128.0/24", "84.201.181.0/24", "84.47.172.0/24"]
              }
              egress {
                protocol       = "TCP"
                port           = 80
                v4_cidr_blocks = ["213.180.204.0/24", "213.180.193.0/24"]
              }
              egress {
                protocol       = "TCP"
                port           = 8443
                v4_cidr_blocks = ["84.47.172.0/24"]
              }
              egress {
                protocol       = "TCP"
                port           = 44445
                v4_cidr_blocks = ["51.250.1.0/24"]
              }
              ingress {
                protocol       = "TCP"
                description    = "ssh"
                v4_cidr_blocks = ["0.0.0.0/0"]
                port           = 22
              }
            }
            
            # Getting information about an image for a VM boot disk
            
            data "yandex_compute_image" "ubuntu" {
              family = "ubuntu-2204-lts"
            }
            
            # Creating a VM boot disk
            
            resource "yandex_compute_disk" "boot-disk" {
              type     = "network-ssd"
              zone     = "ru-central1-a"
              size     = "20"
              image_id = data.yandex_compute_image.ubuntu.id
            }
            
            # Creating a VM
            
            resource "yandex_compute_instance" "my_backup_compute" {
              name               = "backup-instance"
              platform_id        = "standard-v3"
              zone               = "ru-central1-a"
              service_account_id = yandex_iam_service_account.my_sa.id
              network_interface {
                subnet_id          = yandex_vpc_subnet.my_backup_subnet.id
                security_group_ids = [yandex_vpc_security_group.my_backup_security_group.id]
                nat                = true
              }
            
              boot_disk {
                disk_id = yandex_compute_disk.boot-disk.id
              }
            
              resources {
                cores  = 2
                memory = 4
              }
            
              metadata = {
                user-data = "${file("cloud-init.yaml")}"
              }
            }
            
            # Creating a backup policy
            
            resource "yandex_backup_policy" "my_policy" {
              name                = "weekly-backup"
              fast_backup_enabled = true
              retention {
                after_backup = false
              }
              reattempts {
                enabled      = true
                interval     = "1m"
                max_attempts = 10
              }
              scheduling {
                scheme            = "ALWAYS_INCREMENTAL"
                weekly_backup_day = "FRIDAY"
                backup_sets {
                  execute_by_time {
                    repeat_at = ["03:00"]
                    type      = "WEEKLY"
                    weekdays  = ["FRIDAY"]
                  }
                }
              }
              vm_snapshot_reattempts {
                enabled      = true
                interval     = "1m"
                max_attempts = 10
              }
            }
            
            # Associating a backup policy with a VM
            
            resource "yandex_backup_policy_bindings" "my_backup_binding" {
              instance_id = yandex_compute_instance.my_backup_compute.id
              policy_id   = yandex_backup_policy.my_policy.id
            }
            ```

            {% endcut %}

          1. `cloud-init.yaml` VM metadata file:

            {% cut "cloud-init.yaml" %}

            ```yaml
            #cloud-config
            datasource:
             Ec2:
              strict_id: false
            ssh_pwauth: no
            users:
            - name: <username>
              sudo: ALL=(ALL) NOPASSWD:ALL
              shell: /bin/bash
              ssh_authorized_keys:
              - <public_SSH_key>
            packages:
              - curl
              - perl
              - jq
            runcmd:
              - curl https://storage.yandexcloud.net/backup-distributions/agent_installer.sh | sudo bash
            ```

            {% endcut %}

    {% endlist %}

    For more on the properties of resources used in Terraform, see these provider guides:

    * [Service account](../../../iam/concepts/users/service-accounts.md): [yandex_iam_service_account](../../../terraform/resources/iam_service_account.md).
    * Assigning a [role](../../../iam/concepts/access-control/roles.md) to a service account: [yandex_resourcemanager_folder_iam_member](../../../terraform/resources/resourcemanager_folder_iam_member.md).
    * [Network](../../../vpc/concepts/network.md#network): [yandex_vpc_network](../../../terraform/resources/vpc_network.md).
    * [Subnet](../../../vpc/concepts/network.md#subnet): [yandex_vpc_subnet](../../../terraform/resources/vpc_subnet.md).
    * [Security group](../../../vpc/concepts/security-groups.md): [yandex_vpc_security_group](../../../terraform/resources/vpc_security_group.md).
    * [VM image](../../../compute/concepts/image.md) data: [yandex_compute_image](../../../terraform/data-sources/compute_image.md).
    * VM boot [disk](../../../compute/concepts/disk.md): [yandex_compute_disk](../../../terraform/resources/compute_disk.md).
    * [VM instance](../../../compute/concepts/vm.md): [yandex_compute_instance](../../../terraform/resources/compute_instance.md).
    * [Backup policy](../../concepts/policy.md): [yandex_backup_policy](../../../terraform/resources/backup_policy.md). You can create a new policy or use one of those generated automatically upon service activation.
    * Associating a backup policy with a VM: [yandex_backup_policy_bindings](../../../terraform/resources/backup_policy_bindings.md). To associate one of the backup policies created automatically upon service activation, [get](../../operations/policy-vm/get-info.md) its ID.

1. In the `cloud-init.yaml` file, set the following user-defined properties:

    * `name`: VM username, e.g., `vm-user`.
    * `ssh_authorized_keys`: Contents of the [public key](../../../compute/operations/vm-connect/ssh.md#creating-ssh-keys) file. You need to [create](../../../compute/operations/vm-connect/ssh.md#creating-ssh-keys) a key pair for the SSH connection on your own.

1. Create the resources:

    1. In the terminal, navigate to the configuration file directory.
    1. Make sure the configuration is correct using this command:
    
       ```bash
       terraform validate
       ```
    
       If the configuration is valid, you will get this message:
    
       ```bash
       Success! The configuration is valid.
       ```
    
    1. Run this command:
    
       ```bash
       terraform plan
       ```
    
       You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
    1. Apply the configuration changes:
    
       ```bash
       terraform apply
       ```
    
    1. Type `yes` and press **Enter** to confirm the changes.

{% note info %}

When the VM switches to the `Running` status, the Cloud Backup agent will start installing on it. This may take from 5 to 10 minutes.

A policy is linked asynchronously after you create and initialize a VM, as well as install and configure a Cloud Backup agent. This may take up to 10-15 minutes. As a result, the virtual machine will appear in the list of Cloud Backup VMs and in the list of VMs linked to the `weekly-backup` policy.

{% endnote %}

You can monitor the installation progress using the VM [serial port](../../../compute/operations/vm-info/get-serial-port-output.md) in the management console.

## How to delete the resources you created {#clear-out}

To stop paying for the resources you created:

1. Open the `backup-policy-auto-binding.tf` file and delete your infrastructure description from it.
1. Apply the changes:

    1. In the terminal, navigate to the configuration file directory.
    1. Make sure the configuration is correct using this command:
    
       ```bash
       terraform validate
       ```
    
       If the configuration is valid, you will get this message:
    
       ```bash
       Success! The configuration is valid.
       ```
    
    1. Run this command:
    
       ```bash
       terraform plan
       ```
    
       You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
    1. Apply the configuration changes:
    
       ```bash
       terraform apply
       ```
    
    1. Type `yes` and press **Enter** to confirm the changes.

#### Useful links {#see-also}

* [Associating a Yandex Cloud Backup policy with a VM automatically using the management console, CLI, or API](console.md)