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
    • Gateway to Russia
    • Cloud for Startups
    • Education and Science
  • Blog
  • Pricing
  • Documentation
Yandex project
© 2025 Yandex.Cloud LLC
Tutorials
    • All tutorials
    • URL shortener
    • Entering data into storage systems
    • Storing application runtime logs
    • Deploying a web application using the Java Servlet API
    • Developing a Slack bot
    • Developing a Telegram bot
    • Developing a custom integration in API Gateway
    • Developing CRUD APIs for movie services
    • Building a CI/CD pipeline in GitLab
    • Working with an API gateway via WebSocket
    • Creating an interactive serverless application using WebSocket
    • Automatically copying objects from one Object Storage bucket to another
    • Visualizing logs in Grafana using the Cloud Logging plugin
    • Canary release of a Cloud Functions function
    • Interactive debugging of Cloud Functions functions
    • Creating a Node.js function using TypeScript
    • Running a containerized app in Serverless Containers
    • Streaming Yandex Cloud Postbox events to Data Streams and analyzing them using DataLens
    • Using API Gateway to set up speech synthesis in SpeechKit
    • Connecting to YDB from a Cloud Functions function in Python
    • Connecting to a YDB database from a Cloud Functions function in Node.js
    • API Gateway protection with Smart Web Security
    • Deploying a web app with JWT authorization in API Gateway and authentication in Firebase
    • Automatic data upload to Yandex SpeechSense using Yandex Workflows
    • Configuring responses in Cloud Logging and Yandex Cloud Functions
    • Setting up Workflows integration with Tracker, YandexGPT, and Yandex Cloud Postbox
    • Developing functions in Functions Framework and deploying them to Yandex Serverless Containers

In this article:

  • Get your cloud ready
  • Required paid resources
  • Create a service account
  • Create a YDB database
  • Create a function
  • Test the function
  • How to delete the resources you created
  1. Serverless technologies
  2. Connecting to YDB from a Cloud Functions function in Python

Connecting to a Managed Service for YDB database from a Python function in Yandex Cloud Functions

Written by
Yandex Cloud
Improved by
Danila N.
Updated at May 7, 2025
  • Get your cloud ready
    • Required paid resources
  • Create a service account
  • Create a YDB database
  • Create a function
  • Test the function
  • How to delete the resources you created

Create a function with a Python application that runs a simple query against a Yandex Managed Service for YDB database.

A function with an associated service account is authorized in YDB via the metadata service.

The application creates a YDB database connection driver, a session, and a transaction, and runs a query using the ydb library. This library is installed as a dependency when creating a function version. The DB connection parameters are passed to the application via environment variables.

To create a function and connect to the database:

  1. Get your cloud ready.
  2. Create a service account.
  3. Create a YDB database.
  4. Create a function.
  5. Test the function.

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 this scenario includes:

  • Fee for using the function (see Yandex Cloud Functions pricing).
  • Fee for running queries to the database (see Managed Service for YDB pricing).

Create a service accountCreate a service account

Management console
  1. In the management console, select the folder where you want to create your service account.

  2. In the list of services, select Identity and Access Management.

  3. Click Create service account.

  4. Enter a name for the service account, e.g., sa-function. The naming requirements are as follows:

    • It must be from 2 to 63 characters long.
    • It may contain lowercase Latin letters, numbers, and hyphens.
    • It must start with a letter and cannot end with a hyphen.
  5. Click Add role and select editor.

  6. Click Create.

Create a YDB databaseCreate a YDB database

Management console
  1. In the management console, select the folder where you want to create a database.

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

  3. Click Create a database.

  4. Name the database. The naming requirements are as follows:

    • It must be from 2 to 63 characters long.
    • It may contain lowercase Latin letters, numbers, and hyphens.
    • It must start with a letter and cannot end with a hyphen.
  5. Under Database type, select Serverless.

  6. Click Create a database.

    Wait for the DB to start. While being created, the database will have the Provisioning status. Once it is ready for use, its status will change to Running.

  7. Click the name of the database you created.

  8. Under Connection, find the Endpoint field and save its value. You will need it at the next step.

Create a functionCreate a function

Management console
  1. In the Management console, select the folder you want to create a function in.

  2. In the list of services, select Cloud Functions.

  3. Click Create function.

  4. Enter a name and description for the function. The naming requirements are as follows:

    • It must be from 2 to 63 characters long.
    • It may contain lowercase Latin letters, numbers, and hyphens.
    • It must start with a letter and cannot end with a hyphen.
  5. Click Create.

  6. Under Editor, select Python as the runtime environment, disable Add files with code examples, and click Continue.

  7. Under Function code, create a file named index.py and paste the following code into it:

    import os
    import ydb
    import ydb.iam
    
    # Create driver in global space.
    driver = ydb.Driver(
      endpoint=os.getenv('YDB_ENDPOINT'),
      database=os.getenv('YDB_DATABASE'),
      credentials=ydb.iam.MetadataUrlCredentials(),
    )
    
    # Wait for the driver to become active for requests.
    
    driver.wait(fail_fast=True, timeout=5)
    
    # Create the session pool instance to manage YDB sessions.
    pool = ydb.SessionPool(driver)
    
    def execute_query(session):
      # Create the transaction and execute query.
      return session.transaction().execute(
        'select 1 as cnt;',
        commit_tx=True,
        settings=ydb.BaseRequestSettings().with_timeout(3).with_operation_timeout(2)
      )
    
    def handler(event, context):
      # Execute query with the retry_operation helper.
      result = pool.retry_operation_sync(execute_query)
      return {
        'statusCode': 200,
        'body': str(result[0].rows[0].cnt == 1),
      }
    
  8. Under Function code, create a file named requirements.txt and paste the following text into it:

    ydb
    
  9. Specify the entry point: index.handler.

  10. Select a service account, e.g., sa-function.

  11. Configure the environment variables:

    • YDB_ENDPOINT: Enter the first part of the previously saved Endpoint field value (preceding /?database=), e.g., grpcs://ydb.serverless.yandexcloud.net:2135.
    • YDB_DATABASE: Enter the second part of the previously saved Endpoint field value (following /?database=), e.g., /ru-central1/r1gra875baom********/g5n22e7ejfr1********.
  12. Click Save changes.

Test the functionTest the function

Management console
  1. Navigate to the Testing tab.

  2. Click Run test and check out the testing results.

    If a DB connection is established and a query is executed, the function status will change to Done and its output will contain the following text:

    {
      "statusCode": 200,
      "body": "True"
    }
    

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

To stop paying for the resources you created:

  1. Delete the DB.
  2. Delete the function.

Was the article helpful?

Previous
Using API Gateway to set up speech synthesis in SpeechKit
Next
Connecting to a YDB database from a Cloud Functions function in Node.js
Yandex project
© 2025 Yandex.Cloud LLC