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.
Yandex Object Storage
    • All tutorials
    • Getting statistics on object queries with S3 Select
    • Getting website traffic statistics with S3 Select
    • Getting statistics on object queries using Yandex Query
    • Generating a resource-by-resource cost breakdown report using S3 Select
    • Server-side encryption
    • Integrating an L7 load balancer with CDN and Object Storage
    • Blue-green and canary deployment of service versions
    • Analyzing logs in DataLens
    • Mounting buckets to the file system of Yandex Data Processing hosts
    • Using Object Storage in Yandex Data Processing
    • Importing data from Object Storage, processing and exporting to Managed Service for ClickHouse®
    • Mounting a bucket as a disk in Windows
    • Migrating data from Yandex Data Streams using Yandex Data Transfer
    • Using hybrid storage in Yandex Managed Service for ClickHouse®
    • Loading data from Yandex Managed Service for OpenSearch to Yandex Object Storage using Yandex Data Transfer
    • Automatically copying objects from one bucket to another
    • Recognizing audio files in a bucket on a regular basis
    • Training a model in Yandex DataSphere on data from Object Storage
    • Connecting to Object Storage from VPC
    • Migrating data to Yandex Managed Service for PostgreSQL using Yandex Data Transfer
    • Uploading data to Yandex Managed Service for Greenplum® using Yandex Data Transfer
    • Uploading data to Yandex Managed Service for ClickHouse® using Yandex Data Transfer
    • Uploading data to Yandex Managed Service for YDB using Yandex Data Transfer
    • Exchanging data between Yandex Managed Service for ClickHouse® and Yandex Data Processing
    • Uploading data from Yandex Managed Service for YDB using Yandex Data Transfer
    • Hosting a static Gatsby website in Object Storage
    • Migrating a database from Managed Service for PostgreSQL to Object Storage
    • Exchanging data between Yandex Managed Service for ClickHouse® and Yandex Data Processing
    • Importing data from Yandex Managed Service for PostgreSQL to Yandex Data Processing using Sqoop
    • Importing data from Yandex Managed Service for MySQL® to Yandex Data Processing using Sqoop
    • Migrating data from Yandex Object Storage to Yandex Managed Service for MySQL® using Yandex Data Transfer
    • Migrating a database from Yandex Managed Service for MySQL® to Yandex Object Storage
    • Exporting Greenplum® data to a cold storage in Yandex Object Storage
    • Loading data from Yandex Direct to a Yandex Managed Service for ClickHouse® data mart using Yandex Cloud Functions, Yandex Object Storage, and Yandex Data Transfer
    • Migrating data from Elasticsearch to Yandex Managed Service for OpenSearch
    • Uploading Terraform states to Object Storage
    • Locking Terraform states using Managed Service for YDB
    • Visualizing Yandex Query data
    • Publishing game updates
    • VM backups using Hystax Acura
    • Backing up to Object Storage with CloudBerry Desktop Backup
    • Backing up to Object Storage with Duplicati
    • Backing up to Object Storage with Bacula
    • Backing up to Yandex Object Storage with Veeam Backup
    • Backing up to Object Storage with Veritas Backup Exec
    • Managed Service for Kubernetes cluster backups in Object Storage
    • Developing a custom integration in API Gateway
    • URL shortener
    • Storing application runtime logs
    • Developing a skill for Alice and a website with authorization
    • Creating an interactive serverless application using WebSocket
    • Deploying a web application using the Java Servlet API
    • Developing a Telegram bot
    • Replicating logs to Object Storage using Fluent Bit
    • Replicating logs to Object Storage using Data Streams
    • Uploading audit logs to ArcSight SIEM
    • Exporting audit logs to SIEM Splunk systems
    • Creating an MLFlow server for logging experiments and artifacts
    • Operations with data using Yandex Query
    • Federated data queries using Query
    • Recognizing text in image archives using Vision OCR
    • Converting a video to a GIF in Python
    • Automating tasks using Managed Service for Apache Airflow™
    • Processing files with usage details in Yandex Cloud Billing
    • Deploying a web app with JWT authorization in API Gateway and authentication in Firebase
    • Searching for Yandex Cloud events in Yandex Query
    • Searching for Yandex Cloud events in Object Storage
    • Creating an external table from a bucket table using a configuration file
    • Migrating databases from Google BigQuery to Managed Service for ClickHouse®
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Bucket logs
  • Release notes
  • FAQ

In this article:

  • Get your cloud ready
  • Required paid resources
  • Create a service account and static access key
  • Create a bucket
  • Create a Managed Service for YDB database
  • Create a table
  • Install and configure Terraform
  • Install Terraform
  • Get the authentication credentials
  • Create a Terraform configuration file
  • Configure your provider
  • Configure your backend
  • Deploy your configuration
  • Check the saved state
  • Test the state lock
  • How to delete the resources you created
  • See also
  1. Tutorials
  2. Locking Terraform states using Managed Service for YDB

Locking Terraform states using Yandex Managed Service for YDB

Written by
Yandex Cloud
Improved by
Wilya3
Updated at May 7, 2025
  • Get your cloud ready
    • Required paid resources
  • Create a service account and static access key
  • Create a bucket
  • Create a Managed Service for YDB database
    • Create a table
  • Install and configure Terraform
    • Install Terraform
    • Get the authentication credentials
    • Create a Terraform configuration file
    • Configure your provider
  • Configure your backend
  • Deploy your configuration
  • Check the saved state
  • Test the state lock
  • How to delete the resources you created
  • See also

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 Terraform, see this tutorial.

To allow multiple users to manage the infrastructure, you can automatically upload Terraform states and store them in Yandex Object Storage.

When multiple users simultaneously try to access one and the same state from Object Storage, this may lead to conflicts. To prevent such conflicts, you can deploy a database in Yandex Managed Service for YDB and use it to implement Terraform's native state locking mechanism. Every time you use Terraform to update the infrastructure, the state will be automatically locked until the update is applied.

To set up storing Terraform states in Object Storage and locking them with Managed Service for YDB:

  1. Get your cloud ready.
  2. Create a service account and static access key.
  3. Create a bucket.
  4. Create a Managed Service for YDB database.
  5. Install and configure Terraform.
  6. Configure your backend.
  7. Deploy the configuration.
  8. Check the saved state.
  9. Check whether the state is locked.

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

Get your cloud readyGet your cloud ready

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 cost for Terraform states includes:

  • Fees for data storage (see Object Storage pricing).
  • Fee for running queries against the database (see Managed Service for YDB pricing).

The cost of support for the sample infrastructure deployed through Terraform in this tutorial includes:

  • Fee for a continuously running VM (see Yandex Compute Cloud pricing).
  • Fee for a dynamic public IP address (see Yandex Virtual Private Cloud pricing).

If you deploy resources from other Yandex Cloud services, the cost will change as per the respective service plans.

Create a service account and static access keyCreate a service account and static access key

  1. Create a service account with the storage.editor and ydb.admin roles for the folder specified in the provider settings.
  2. Get a static access key. Save the key ID and secret key: you will need them later as you follow this tutorial.

Create a bucketCreate a bucket

Create a bucket with restricted access. This bucket will store the Terraform state file.

Create a Managed Service for YDB databaseCreate a Managed Service for YDB database

Create a serverless DB named state-lock-db.

Create a tableCreate a table

Management console
AWS CLI
  1. In the management console, select the folder where the database is located.

  2. From the list of services, select Managed Service for YDB.

  3. From the DB list, select state-lock-db.

  4. Go the Navigation tab.

  5. In the top-right corner, click Create and select Table.

  6. Specify the table name: state-lock-table.

  7. In the table properties, opt for the document table as the Table type.

  8. Under Columns, specify:

    • Name: LockID.
    • Type: String.
    • Partitioning key: Enable this option by ticking the checkbox.

    Delete the other columns.

  9. Click Create table.

To create a table through the AWS CLI:

  1. Run this command:

    aws dynamodb create-table \
      --table-name <table_name> \
      --attribute-definitions \
        AttributeName=LockID,AttributeType=S \
      --key-schema \
        AttributeName=LockID,KeyType=HASH \
      --endpoint <DB_document-api-endpoint>
    

    Where:

    • --table-name: Table name
    • --attribute-definitions: Column properties:
      • AttributeName: Column name.
      • AttributeType: Data type. In our example, we are using string data (S).
    • --key-schema: Key schema for the column:
      • AttributeName: Column name.
      • KeyType: Key type. In our example, we are using a partitioning key (HASH).
    • --endpoint: Document API endpoint of the DB. You can find it on the database main page under Document API endpoint.

Install and configure TerraformInstall and configure Terraform

Install TerraformInstall Terraform

Windows
Linux
macOS

Use one of the following methods:

  • Download the Terraform distribution and follow this guide to install it.

  • Install Terraform using the Chocolatey package manager and the command below:

    choco install terraform
    

Download the Terraform distribution and follow this guide to install it.

Use one of the following methods:

  • Download the Terraform distribution and follow this guide to install it.

  • Install Terraform using the Homebrew package manager and the command below:

    brew install terraform
    

Get the authentication credentialsGet the authentication credentials

Use a service account to manage the Yandex Cloud infrastructure using Terraform. It will help you flexibly configure access permissions to resources.

You can also use Terraform under your Yandex account or a federated account, but this method is less secure. For more information, see the end of this section.

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

  2. Set up the CLI profile to perform operations under the service account:

    CLI
    1. Create an authorized key for your service account and save the file:

      yc iam key create \
        --service-account-id <service_account_ID> \
        --folder-name <service_account_folder_name> \
        --output key.json
      

      Where:

      • service-account-id: Service account ID.
      • folder-name: Name of the folder in which the service account was created.
      • output: Name of the file with the authorized key.

      Result:

      id: aje8nn871qo4********
      service_account_id: ajehr0to1g8b********
      created_at: "2022-09-14T09:11:43.479156798Z"
      key_algorithm: RSA_2048
      
    2. Create a CLI profile to run operations on behalf of the service account. Name the profile:

      yc config profile create <profile_name>
      

      Result:

      Profile 'sa-terraform' created and activated
      
    3. Set the profile configuration:

      yc config set service-account-key key.json
      yc config set cloud-id <cloud_ID>
      yc config set folder-id <folder_ID>
      

      Where:

      • service-account-key: File with the service account authorized key.
      • cloud-id: Cloud ID.
      • folder-id: Folder ID.
  3. Add the credentials to the environment variables:

    Bash
    PowerShell
    export YC_TOKEN=$(yc iam create-token)
    export YC_CLOUD_ID=$(yc config get cloud-id)
    export YC_FOLDER_ID=$(yc config get folder-id)
    

    Where:

    • YC_TOKEN: IAM token.
    • YC_CLOUD_ID: Cloud ID.
    • YC_FOLDER_ID: Folder ID.
    $Env:YC_TOKEN=$(yc iam create-token)
    $Env:YC_CLOUD_ID=$(yc config get cloud-id)
    $Env:YC_FOLDER_ID=$(yc config get folder-id)
    

    Where:

    • YC_TOKEN: IAM token.
    • YC_CLOUD_ID: Cloud ID.
    • YC_FOLDER_ID: Folder ID.

    Note

    The IAM token lifetime does not exceed 12 hours; however, we recommend requesting it more often, such as once per hour.

Managing resources on behalf of a Yandex account or a federated account

Warning

Managing resources under a user's Yandex account or federated account is less secure than under a service account.

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.

If you use a federated account, authenticate with the CLI on behalf of the federated user.

Add the credentials to the environment variables:

Bash
PowerShell
export YC_TOKEN=$(yc iam create-token)
export YC_CLOUD_ID=$(yc config get cloud-id)
export YC_FOLDER_ID=$(yc config get folder-id)

Where:

  • YC_TOKEN: IAM token.
  • YC_CLOUD_ID: Cloud ID.
  • YC_FOLDER_ID: Folder ID.
$Env:YC_TOKEN=$(yc iam create-token)
$Env:YC_CLOUD_ID=$(yc config get cloud-id)
$Env:YC_FOLDER_ID=$(yc config get folder-id)

Where:

  • YC_TOKEN: IAM token.
  • YC_CLOUD_ID: Cloud ID.
  • YC_FOLDER_ID: Folder ID.

Note

The IAM token lifetime does not exceed 12 hours; however, we recommend requesting it more often, such as once per hour.

Create a Terraform configuration fileCreate a Terraform configuration file

  1. Create a directory with any name, for example, cloud-terraform. It will store the Terraform configuration files.
  2. Create a configuration file with the .tf extension in this directory, for example, example.tf.

Configure your providerConfigure your provider

Note

These settings apply to Terraform 0.13 and higher. We recommend using the latest stable version of Terraform.

  1. If you previously configured a provider from the HashiCorp registry, save its settings:

    Linux/macOS
    Windows
    mv ~/.terraformrc ~/.terraformrc.old
    
    mv $env:APPDATA/terraform.rc $env:APPDATA/terraform.rc.old
    
  2. Specify the source the provider will be installed from.

    Linux/macOS
    Windows

    Open the Terraform CLI configuration file:

    nano ~/.terraformrc
    

    Note

    The .terraformrc file must be in the user's home root folder, e.g., /home/user/ or /User/user/.

    Open the Terraform CLI configuration file named terraform.rc in your user's %APPDATA% folder.

    To find out the absolute path to the %APPDATA% folder, run the echo %APPDATA% command for cmd or the $env:APPDATA command for PowerShell.

    Add the following section to the file:

    provider_installation {
      network_mirror {
        url = "https://terraform-mirror.yandexcloud.net/"
        include = ["registry.terraform.io/*/*"]
      }
      direct {
        exclude = ["registry.terraform.io/*/*"]
      }
    }
    

    For more information about setting up mirrors, see the documentation.

  3. Add the following sections at the top of the .tf configuration file:

    terraform {
      required_providers {
        yandex = {
          source = "yandex-cloud/yandex"
        }
      }
      required_version = ">= 0.13"
    }
    
    provider "yandex" {
      zone = "<default_availability_zone>"
    }
    

    Where:

    • source: Provider's global source address.
    • required_version: Minimum Terraform version the provider is compatible with.
    • provider: Provider name.
    • zone: Availability zone where all cloud resources will be created by default.
  4. Run the terraform init command in the folder containing the .tf configuration file. This command initializes the providers specified in the configuration files and allows you to work with the provider resources and data sources.

If the provider installation failed, create a support request stating provider name and version.

If you used the .terraform.lock.hcl file, prior to the initialization, run the terraform providers lock command specifying the URL of the mirror to upload the provider from and the platforms the configuration will run on:

terraform providers lock -net-mirror=https://terraform-mirror.yandexcloud.net -platform=<platform_1_name> -platform=<platform_2_name> yandex-cloud/yandex

Where:

  • -net-mirror: Address of the mirror to upload the provider from.
  • -platform: Platforms to use the configuration on. The possible values include:
    • windows_amd64: 64-bit Windows
    • linux_amd64: 64-bit Linux
    • darwin_arm64: 64-bit macOS

If you used the Terraform modules, first run terraform init, then delete the lock file. After that, run the terraform providers lock command.

For more information about the terraform providers lock command, see the Terraform documentation.

Configure your backendConfigure your backend

Note

The following backend settings apply in Terraform 1.6.3 and higher.

To save the Terraform state in Object Storage and enable state locking:

  1. Add the key ID and secret key you got earlier to environment variables:

    Bash
    PowerShell
    export ACCESS_KEY="<key_ID>"
    export SECRET_KEY="<secret_key>"
    
  2. Add the provider and backend settings to the configuration file:

    terraform {
      required_providers {
        yandex = {
          source = "yandex-cloud/yandex"
        }
      }
      required_version = ">= 0.13"
    
      backend "s3" {
        endpoints = {
          s3       = "https://storage.yandexcloud.net"
          dynamodb = "<DB_Document_API_endpoint>"
        }
        bucket            = "<bucket_name>"
        region            = "ru-central1"
        key               = "<path_to_state_file_in_bucket>/<state_file_name>.tfstate"
    
        dynamodb_table = "<table_name>"
    
        skip_region_validation      = true
        skip_credentials_validation = true
        skip_requesting_account_id  = true # This option is required for Terraform 1.6.1 or higher.
        skip_s3_checksum            = true # This option is required to describe a backend for Terraform 1.6.3 or higher.
      }
    }
    
    provider "yandex" {
      zone = "<default_availability_zone>"
    }
    

    Where:

    • bucket: Bucket name.
    • dynamodb: Document API of the DB, formatted as https://docapi.serverless.yandexcloud.net/ru-central1/b1gia87mbaom********.
    • key: Object key in the bucket (name and path to the Terraform state file in the bucket).
    • dynamodb_table: Table name.

    To read more about the state storage backend, see the Terraform website.

  3. Run the following command in the folder with the configuration file:

    terraform init
    

Deploy your configurationDeploy your configuration

In this example, you will create a VM named terraform-vm connected to subnet-1 in the ru-central1-d availability zone. This subnet will be part of the cloud network named network-1.

This VM instance will have 2 cores and 4 GB RAM. It will automatically get a public and private IP addresses from the 192.168.10.0/24 range in subnet-1. The VM will run Ubuntu and host the public part of the key to enable SSH access.

  1. Save the following configuration as a separate example-vm.tf file in the folder with the backend configuration file:

    resource "yandex_compute_image" "ubuntu_2004" {
      source_family = "ubuntu-2004-lts"
    }
    
    resource "yandex_compute_disk" "boot-disk" {
      name     = "boot-disk"
      type     = "network-hdd"
      zone     = "ru-central1-d"
      size     = "20"
      image_id = yandex_compute_image.ubuntu_2004.id
    }
    
    resource "yandex_compute_instance" "vm-1" {
      name = "terraform-vm"
    
      resources {
        cores  = 2
        memory = 4
      }
    
      boot_disk {
        disk_id = yandex_compute_disk.boot-disk.id
      }
    
      network_interface {
        subnet_id = yandex_vpc_subnet.subnet-1.id
        nat       = true
      }
    
      metadata = {
        user-data = "#cloud-config\nusers:\n  - name: <username>\n    groups: sudo\n    shell: /bin/bash\n    sudo: 'ALL=(ALL) NOPASSWD:ALL'\n    ssh_authorized_keys:\n      - ${file("<path_to_public_SSH_key>")}"
      }
    }
    
    resource "yandex_vpc_network" "network-1" {
      name = "network1"
    }
    
    resource "yandex_vpc_subnet" "subnet-1" {
      name           = "subnet1"
      zone           = "ru-central1-d"
      network_id     = yandex_vpc_network.network-1.id
      v4_cidr_blocks = ["192.168.10.0/24"]
    }
    
    output "internal_ip_address_vm_1" {
      value = yandex_compute_instance.vm-1.network_interface.0.ip_address
    }
    
    output "external_ip_address_vm_1" {
      value = yandex_compute_instance.vm-1.network_interface.0.nat_ip_address
    }
    
    output "subnet-1" {
      value = yandex_vpc_subnet.subnet-1.id
    }
    
  2. Check the configuration using the terraform plan command.

  3. Deploy your configuration using the terraform apply command.

Check the saved stateCheck the saved state

Make sure the state file is uploaded to Yandex Object Storage:

Management console
  1. Go to the management console and select the folder containing the bucket you created.
  2. Select Object Storage.
  3. In the bucket list, select the bucket you saved the Terraform state to.
  4. Make sure the state file is in the bucket.

Test the state lockTest the state lock

Try to update the infrastructure simultaneously with another user. If the lock mechanism works correctly, Terraform will return the following message after running terraform apply:

member Error: Error acquiring the state lock

member Error message: ConditionalCheckFailedException: Condition not satisfied
member Lock Info:
member   ID:        <...>
member   Path:      terraform-object-storage-tutorial/TF/cloud-storage.tfstate
member   Operation: OperationTypeApply
member   Who:       LD\user@i7293
member   Version:   1.4.2
member   Created:   <...>
member   Info:

member Terraform acquires a state lock to protect the state from being written
member by multiple users at the same time. Please resolve the issue above and try
member again. For most commands, you can disable locking with the "-lock=false"
member flag, but this is not recommended.

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

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

  1. Delete the table from the database.
  2. Delete state-lock-db.
  3. Delete the bucket.

See alsoSee also

  • Getting started with Terraform.
  • Uploading Terraform states to Object Storage.
  • Using Yandex Cloud modules in Terraform.
  • Terraform data sources.

Was the article helpful?

Previous
Uploading Terraform states to Object Storage
Next
Overview
© 2025 Direct Cursus Technology L.L.C.