[Yandex Cloud documentation](../../../index.md) > [Tutorials](../../index.md) > [Storing and recovering data](../index.md) > [Associating a Cloud Backup policy with a VM automatically](index.md) > Management console, CLI, and API

# Associating a Yandex Cloud Backup policy with a VM automatically using the management console, CLI, or API

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 a service account](#create-sa).
1. [Create a cloud network and subnets](#create-network).
1. [Create and configure a security group](#create-sg).
1. [Create a backup policy](#create-policy).
1. [Create a VM](#create-vm).

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](../../../backup/pricing.md#rules)).

## Activate Cloud Backup {#service-activate}

{% note info %}

To activate the service, you need _at least_ the `backup.user` [role](../../../backup/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 a service account {#create-sa}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you activated Cloud Backup.
  1. Navigate to **Identity and Access Management**.
  1. Click **Create service account**.
  1. Enter `backup-sa` as the [service account name](../../../iam/concepts/users/service-accounts.md).
  1. Click ![plus-sign](../../../_assets/console-icons/plus.svg) **Add role** and select [`backup.user`](../../../backup/security/index.md#backup-user).
  1. Click **Create**.

- Yandex Cloud 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. Create a service account named `backup-sa`:

      ```bash
      yc iam service-account create --name backup-sa
      ```

      Result:

      ```bash
      id: ajehb3tcdfa1********
      folder_id: b1g86q4m5vej********
      created_at: "2024-07-22T16:05:14.237381531Z"
      name: backup-sa
      ```

      For more information about the `yc iam service-account create` command, see the [CLI reference](../../../cli/cli-ref/iam/cli-ref/service-account/create.md).

  1. Assign the `backup.user` role for the folder to the service account:

      ```bash
      yc resource-manager folder add-access-binding <folder_ID> \
        --role backup.user \
        --subject serviceAccount:<service_account_ID>
      ```

      Result:

      ```bash
      done (3s)
      effective_deltas:
        - action: ADD
          access_binding:
            role_id: backup.user
            subject:
              id: ajehb3tcdfa1********
              type: serviceAccount
      ```

      For more information about the `yc resource-manager folder add-access-binding` command, see the [CLI reference](../../../cli/cli-ref/resource-manager/cli-ref/folder/add-access-binding.md).

- API {#api}

  To create a service account, use the [create](../../../iam/api-ref/ServiceAccount/create.md) REST API method for the [ServiceAccount](../../../iam/api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/Create](../../../iam/api-ref/grpc/ServiceAccount/create.md) gRPC API call.

  To assign the `backup.user` role for a folder to a service account, use the [setAccessBindings](../../../iam/api-ref/ServiceAccount/setAccessBindings.md) method for the [ServiceAccount](../../../iam/api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/SetAccessBindings](../../../iam/api-ref/grpc/ServiceAccount/setAccessBindings.md) gRPC API call.

{% endlist %}

## Create a cloud network and subnets {#create-network}

Create a [cloud network](../../../vpc/concepts/network.md#network) with a [subnet](../../../vpc/concepts/network.md#subnet) in the [availability zone](../../../overview/concepts/geo-scope.md) that will host your VM.

{% 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 cloud network.
  1. Navigate to **Virtual Private Cloud**.
  1. At the top right, click **Create network**.
  1. In the **Name** field, specify `cloud-network`.
  1. In the **Advanced** field, select **Create subnets**.
  1. Click **Create network**.

- Yandex Cloud CLI {#cli}

  1. Create a cloud network named `cloud-network`:

      ```bash
      yc vpc network create cloud-network
      ```

      Result:

      ```bash
      id: enptrcle5q3d********
      folder_id: b1g9hv2loamq********
      created_at: "2024-06-08T09:25:03Z"
      name: cloud-network
      default_security_group_id: enpbsnnop4ak********
      ```

      For more information about the `yc vpc network create` command, see the [CLI reference](../../../cli/cli-ref/vpc/cli-ref/network/create.md).

  1. Create the `cloud-network-ru-central1-d` subnet in the `ru-central1-d` availability zone:

      ```bash
      yc vpc subnet create cloud-network-ru-central1-d \
        --zone ru-central1-d \
        --network-name cloud-network \
        --range 10.1.0.0/16
      ```

      Result:

      ```bash
      id: e9bnnssj8sc8********
      folder_id: b1g9hv2loamq********
      created_at: "2024-06-08T09:27:00Z"
      name: cloud-network-ru-central1-d
      network_id: enptrcle5q3d********
      zone_id: ru-central1-d
      v4_cidr_blocks:
      - 10.1.0.0/16
      ```

      For more information about the `yc vpc subnet create` command, see the [CLI reference](../../../cli/cli-ref/vpc/cli-ref/subnet/create.md).

- API {#api}

  1. Create a network named `cloud-network` using the [create](../../../vpc/api-ref/Network/create.md) REST API method for the [Network](../../../vpc/api-ref/Network/index.md) resource or the [NetworkService/Create](../../../vpc/api-ref/grpc/Network/create.md) gRPC API call.
  1. Create the `cloud-network-ru-central1-d` subnet using the [create](../../../vpc/api-ref/Subnet/create.md) REST API method for the [Subnet](../../../vpc/api-ref/Subnet/index.md) resource or the [SubnetService/Create](../../../vpc/api-ref/grpc/Subnet/create.md) gRPC API call.

{% endlist %}

## Create and configure a security group {#create-sg}

For the [Cloud Backup agent](../../../backup/concepts/agent.md) to exchange data with the [backup provider](../../../backup/concepts/index.md#providers) servers, the security group must contain the rules that allow network access to the IP addresses of the Cloud Backup resources.

The security group will also include a rule for VM access over SSH.

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), go to the folder where you want to create a VM connected to Cloud Backup.
  1. Navigate to **Virtual Private Cloud**.
  1. In the left-hand panel, select ![image](../../../_assets/console-icons/shield.svg) **Security groups**.
  1. Click **Create security group**.
  1. In the **Name** field, specify `backup-sg`.
  1. In the **Network** field, select `cloud-network`.
  1. Under **Rules**, navigate to the **Egress** tab and click **Add**.
  1. Add the following outbound rules one by one:

      Port range | Protocol | Destination name | CIDR blocks
      --- | --- | --- | ---
      `80` | `TCP` | `CIDR` | `213.180.193.0/24`
      `80` | `TCP` | `CIDR` | `213.180.204.0/24`
      `443` | `TCP` | `CIDR` | `84.47.172.0/24`
      `443` | `TCP` | `CIDR` | `84.201.181.0/24`
      `443` | `TCP` | `CIDR` | `178.176.128.0/24`
      `443` | `TCP` | `CIDR` | `213.180.193.0/24`
      `443` | `TCP` | `CIDR` | `213.180.204.0/24`
      `7770-7800` | `TCP` | `CIDR` | `84.47.172.0/24`
      `8443` | `TCP` | `CIDR` | `84.47.172.0/24`
      `44445` | `TCP` | `CIDR` | `51.250.1.0/24`
      
      
      
      {% note tip %}
      
      When installing the [Cloud Backup agent](../../../backup/concepts/agent.md) on your VM or BareMetal server, you might need to install missing software components from the internet. To do this, add the following outgoing traffic rule to the [security group](../../../vpc/concepts/security-groups.md):
      * **Port range**: `0-65535`.
      * **Protocol**: `Any`.
      * **Destination name**: `CIDR`.
      * **CIDR blocks**: `0.0.0.0/0`.
      
      Once the Cloud Backup agent is installed, you can delete this rule.
      
      To access the VM over [SSH](../../../compute/operations/vm-connect/ssh.md), add the following incoming traffic rule:
      * **Port range**: `22`.
      * **Protocol**: `Any`.
      * **Destination name**: `CIDR`.
      * **CIDR blocks**: `0.0.0.0/0`.
      
      {% endnote %}

  1. Add the following inbound rule to enable VM access over SSH:

      Port range | Protocol | Source | CIDR blocks
      --- | --- | --- | ---
      `22` | `Any` | `CIDR` | `0.0.0.0/0`

  1. Click **Create**.

- Yandex Cloud CLI {#cli}

  Run this command:

  ```bash
  yc vpc security-group create backup-sg \
    --network-name network-1 \
    --rule "direction=egress,port=80,protocol=tcp,v4-cidrs=[213.180.193.0/24]" \
    --rule "direction=egress,port=80,protocol=tcp,v4-cidrs=[213.180.204.0/24]" \
    --rule "direction=egress,port=443,protocol=tcp,v4-cidrs=[84.47.172.0/24]" \
    --rule "direction=egress,port=443,protocol=tcp,v4-cidrs=[84.201.181.0/24]" \
    --rule "direction=egress,port=443,protocol=tcp,v4-cidrs=[178.176.128.0/24]" \
    --rule "direction=egress,port=443,protocol=tcp,v4-cidrs=[213.180.193.0/24]" \
    --rule "direction=egress,port=443,protocol=tcp,v4-cidrs=[213.180.204.0/24]" \
    --rule "direction=egress,from-port=7770,to-port=7800,protocol=tcp,v4-cidrs=[84.47.172.0/24]" \
    --rule "direction=egress,port=8443,protocol=tcp,v4-cidrs=[84.47.172.0/24]" \
    --rule "direction=egress,port=44445,protocol=tcp,v4-cidrs=[51.250.1.0/24]" \
    --rule "direction=ingress,port=22,protocol=any,v4-cidrs=[0.0.0.0/0]"
  ```

  Result:

  ```bash
  id: enp0v73fe8fs********
  folder_id: b1g86q4m5vej********
  created_at: "2024-07-22T20:17:43Z"
  name: backup-sgg
  network_id: enp3srbi9u49********
  status: ACTIVE
  rules:
  - id: enpporsovuhj********
      direction: EGRESS
      ports:
        from_port: "80"
        to_port: "80"
      protocol_name: TCP
      protocol_number: "6"
      cidr_blocks:
        v4_cidr_blocks:
          - 213.180.193.0/24
  - id: enp7p6asol5i********
      direction: EGRESS
      ports:
        from_port: "80"
        to_port: "80"
      protocol_name: TCP
      protocol_number: "6"
      cidr_blocks:
        v4_cidr_blocks:
          - 213.180.204.0/24
  ...
  - id: enp36mip5nhe********
      direction: INGRESS
      ports:
        from_port: "22"
        to_port: "22"
      protocol_name: ANY
      protocol_number: "-1"
      cidr_blocks:
        v4_cidr_blocks:
          - 0.0.0.0/0
  ```

  For more information about the `yc vpc security-group create` command, see the [CLI reference](../../../cli/cli-ref/vpc/cli-ref/security-group/create.md).

- API {#api}

  To create a security group, use the [create](../../../vpc/api-ref/SecurityGroup/create.md) REST API method for the [SecurityGroup](../../../vpc/api-ref/SecurityGroup/index.md) resource or the [SecurityGroupService/Create](../../../vpc/api-ref/grpc/SecurityGroup/create.md) gRPC API call.

{% endlist %}

## Create a backup policy {#create-policy}

You can create a new policy or use one of those automatically created upon service activation.

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) where you want to create a backup policy.
  1. Navigate to **Cloud Backup**.
  1. Navigate to the ![policies](../../../_assets/console-icons/calendar.svg) **Backup policies** tab.
  1. Click **Create policy**.
  1. Specify the following policy properties:

      * **Name**: `weekly-backup`.
      * **Backup type**: `Incremental`.
      * **Launch schedule**: `Fixed schedule`.
      * **Frequency**: `Weekly`.
      * **Days of the week**: `Fri`.
      * **Start time**: `03:00`.
      * **Copy retention**: `Retain all copies`.

  1. Click **Save**.

- CLI {#cli}

  1. Describe the configuration of the backup policy you are creating in the `backup-policy-scheme.json` file.

      ```json
      {
        "compression": "NORMAL",
        "format": "AUTO",
        "multiVolumeSnapshottingEnabled": true,
        "preserveFileSecuritySettings": true,
        "reattempts": {
          "enabled": true,
          "interval": {
            "type": "SECONDS",
            "count": "30"
          },
          "maxAttempts": "30"
        },
        "silentModeEnabled": true,
        "splitting": {
          "size": "1099511627776"
        },
        "vmSnapshotReattempts": {
          "enabled": true,
          "interval": {
            "type": "MINUTES",
            "count": "5"
          },
          "maxAttempts": "3"
        },
        "vss": {
          "enabled": true,
          "provider": "TARGET_SYSTEM_DEFINED"
        },
        "archive": {
          "name": "'[Machine Name]-[Plan ID]-[Unique ID]A'"
        },
        "performanceWindow": {
          "enabled": true
        },
        "scheduling": {
          "backupSets": [
            {
              "time": {
                "weekdays": [
                  "FRIDAY"
                ],
                "repeatAt": [
                  {
                    "hour": "3"
                  }
                ],
                "type": "WEEKLY"
              }
            }
          ],
          "enabled": true,
          "maxParallelBackups": "2",
          "randMaxDelay": {
            "type": "MINUTES",
            "count": "30"
          },
          "scheme": "ALWAYS_INCREMENTAL",
          "weeklyBackupDay": "MONDAY"
        },
        "cbt": "ENABLE_AND_USE",
        "fastBackupEnabled": true,
        "quiesceSnapshottingEnabled": true
      }
      ```

  1. Create a backup policy:

      ```bash
      yc backup policy create \
        --name weekly-backup \
        --settings-from-file ./backup-policy-scheme.json
      ```

      Result:

      ```text
      id: cdgo5vytuw57********
      name: weekly-backup
      created_at: "2024-07-23T20:34:37Z"
      updated_at: "2024-07-23T20:34:37Z"
      enabled: true
      settings:
        compression: NORMAL
        format: AUTO
        multi_volume_snapshotting_enabled: true
        preserve_file_security_settings: true
        reattempts:
          enabled: true
          interval:
            type: SECONDS
            count: "30"
          max_attempts: "30"
        silent_mode_enabled: true
        splitting:
          size: "1099511627776"
        vm_snapshot_reattempts:
          enabled: true
          interval:
            type: MINUTES
            count: "5"
          max_attempts: "3"
        vss:
          enabled: true
          provider: TARGET_SYSTEM_DEFINED
        archive:
          name: '''[Machine Name]-[Plan ID]-[Unique ID]A'''
        performance_window:
          enabled: true
        retention: {}
        scheduling:
          backup_sets:
            - time:
                weekdays:
                  - FRIDAY
                repeat_at:
                  - hour: "3"
                type: WEEKLY
              type: TYPE_AUTO
          enabled: true
          max_parallel_backups: "2"
          rand_max_delay:
            type: MINUTES
            count: "30"
          scheme: ALWAYS_INCREMENTAL
          weekly_backup_day: MONDAY
        cbt: ENABLE_AND_USE
        fast_backup_enabled: true
        quiesce_snapshotting_enabled: true
      folder_id: b1g86q4m5vej********
      ```

      Save the policy `id`.

      For more information about the `yc backup policy create` command, see the [CLI reference](../../../cli/cli-ref/backup/cli-ref/policy/create.md).

- API {#api}

  To create a [backup policy](../../../backup/concepts/policy.md), use the [create](../../../backup/backup/api-ref/Policy/create.md) REST API method for the [Policy](../../../backup/backup/api-ref/Policy/index.md) resource or the [PolicyService/Create](../../../backup/backup/api-ref/grpc/Policy/create.md) gRPC API call.

{% endlist %}

## Create a VM {#create-vm}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) where you want to create your VM.
  1. Navigate to **Compute Cloud**.
  1. In the left-hand panel, select ![image](../../../_assets/console-icons/server.svg) **Virtual machines**.
  1. Click **Create virtual machine**.
  1. Under **Boot disk image**, in the **Product search** field, enter `Ubuntu 22.04 LTS` and select a public [Ubuntu 22.04 LTS](https://yandex.cloud/en/marketplace/products/yc/ubuntu-22-04-lts) image.
  1. Under **Location**, select the `ru-central1-d` [availability zone](../../../overview/concepts/geo-scope.md).
  1. Under **Network settings**:

      * In the **Subnet** field, select the network named `cloud-network` and the subnet named `cloud-network-ru-central1-d`.
      * In the **Public IP address** field, leave the `Auto` value to assign a random external IP address from the Yandex Cloud pool.
      * In the **Security groups** field, select `backup-sg`.
  1. Under **Access**, select **SSH key** and specify the VM access credentials:

      * In the **Login** field, enter the username: `vm-user`.
      * In the **SSH key** field, select the SSH key saved in your [organization user](../../../organization/concepts/membership.md) profile.
        
        If there are no SSH keys in your profile or you want to add a new key:
        
        1. Click **Add key**.
        1. Enter a name for the SSH key.
        1. Select one of the following:
        
            * `Enter manually`: Paste the contents of the public SSH key. You need to [create](../../../compute/operations/vm-connect/ssh.md#creating-ssh-keys) an SSH key pair on your own.
            * `Load from file`: Upload the public part of the SSH key. You need to create an SSH key pair on your own.
            * `Generate key`: Automatically create an SSH key pair.
            
              When adding a new SSH key, an archive containing the key pair will be created and downloaded. In Linux or macOS-based operating systems, unpack the archive to the `/home/<user_name>/.ssh` directory. In Windows, unpack the archive to the `C:\Users\<user_name>/.ssh` directory. You do not need additionally enter the public key in the management console.
        
        1. Click **Add**.
        
        The system will add the SSH key to your organization user profile. If the organization has [disabled](../../../organization/operations/os-login-access.md) the ability for users to add SSH keys to their profiles, the added public SSH key will only be saved in the user profile inside the newly created resource.
  1. Enable **Backup** and select the backup policy you [created earlier](#create-policy) in the **Backup policies** field.
  1. Under **General information**, specify the VM name: `backup-instance`.
  1. Expand the **Additional** section and select the `backup-sa` service account in the **Service account** field.
  1. Click **Create VM**.

- Yandex Cloud CLI {#cli}

  {% note info %}
  
  The commands [`yc compute instance create`](../../../cli/cli-ref/compute/cli-ref/instance/create.md) | [`create-with-container`](../../../cli/cli-ref/compute/cli-ref/instance/create-with-container.md) | [`update`](../../../cli/cli-ref/compute/cli-ref/instance/update.md) | [`add-metadata`](../../../cli/cli-ref/compute/cli-ref/instance/add-metadata.md) support substitution of environment variable values into VM metadata. When you execute a Yandex Cloud CLI command, these values, specified in the `user-data` key in `$<variable_name>` format, will be substituted into the VM metadata from the environment variables of the environment the command is executed in. 
  
  To change such behavior, i.e. to provide a variable name to the VM metadata in `$<variable_name>` format rather than take the variable value from the CLI command runtime environment, use the two-dollar syntax, e.g., `$$<variable_name>`.
  
  For more information, see [Specifics of providing environment variables in metadata via the CLI](../../../compute/concepts/metadata/sending-metadata.md#environment-variables).
  
  {% endnote %}

  1. Describe the custom metadata configuration in the `user-data.yaml` file:

      ```yaml
      #cloud-config
      datasource:
        Ec2:
        strict_id: false
      ssh_pwauth: no
      users:
      - name: vm-user
        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
      ```

  1. Save the `weekly-backup` policy ID in the `cloudbackup.json` file:

      ```json
      {"initialPolicies": ["<weekly-backup_policy_ID>"]}
      ```

      To learn more about getting a policy ID, see [this guide](../../../backup/operations/policy-vm/get-info.md).

  1. Run this command:

      ```bash
      yc compute instance create \
        --name backup-instance \
        --zone ru-central1-d \
        --network-interface subnet-name=cloud-network-ru-central1-d,security-group-ids=<backup-sg_security_group_ID>,ipv4-address=auto,nat-ip-version=ipv4 \
        --create-boot-disk image-folder-id=standard-images,image-family=ubuntu-2204-lts,size=15 \
        --metadata-from-file user-data=./user-data.yaml,cloudbackup=./cloudbackup.json \
        --service-account-name backup-sa
      ```

      For more information about the `yc compute instance create` command, see the [CLI reference](../../../cli/cli-ref/compute/cli-ref/instance/create.md).

- API {#api}

  To create a VM, use the [create](../../../compute/api-ref/Instance/create.md) REST API method for the [Instance](../../../compute/api-ref/Instance/index.md) resource or the [InstanceService/Create](../../../compute/api-ref/grpc/Instance/create.md) gRPC API call.

  In the body of your request, provide the following:

  * In the `metadata` field, the `user-data` object containing the custom metadata configuration with the Cloud Backup agent installation script.
  * In the `cloudbackup` field, the backup policy ID. To learn more about getting a policy ID, see [this guide](../../../backup/operations/policy-vm/get-info.md).

  Use `\n` as a line separator.

  {% cut "Request body example" %}

  ```json
  {
    "folderId": "<folder_ID>",
    "name": "backup-instance",
    "zoneId": "ru-central1-d",
    "platformId": "standard-v3",
    "resourcesSpec": {
      "memory": "2147483648",
      "cores": "2"
    },
    "metadata": {
      "user-data": "#cloud-config\ndatasource:\nEc2:\n  strict_id: false\nssh_pwauth: no\nusers:\n- name: vm-user\n  shell: /bin/bash\n  sudo: ALL=(ALL) NOPASSWD:ALL\n  ssh_authorized_keys:\n  - <public_SSH_key>\npackages:\n  - curl\n  - perl\n  - jq\nruncmd:\n  - curl https://storage.yandexcloud.net/backup-distributions/agent_installer.sh | sudo bash",
      "cloudbackup": "{\"initialPolicies\": [\"<policy_ID>\"]}"
    },
    "bootDiskSpec": {
      "diskSpec": {
        "size": "16106127360",
        "imageId": "fd8ljvsrm3l1********"
      }
    },
    "networkInterfaceSpecs": [
      {
        "subnetId": "<subnet_ID>",
        "primaryV4AddressSpec": {
          "oneToOneNatSpec": {
            "ipVersion": "IPV4"
          }
        },
        "securityGroupIds": [
          "<security_group_ID>"
        ]
      }
    ],
    "serviceAccountId": "<service_account_ID>"
  }
  ```

  {% endcut %}

{% endlist %}

{% 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. [Delete](../../../backup/operations/delete-vm.md) the VM from Cloud Backup.
1. [Delete](../../../compute/operations/vm-control/vm-delete.md) the VM from Compute Cloud.
1. [Delete](../../../vpc/operations/address-delete.md) the static public IP address if you reserved one.
1. [Delete](../../../backup/operations/backup-vm/delete.md) VM backups, if any.

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

* [Associating a Yandex Cloud Backup policy with a VM automatically using Terraform](terraform.md)