Yandex Cloud
Search
Contact UsTry it for free
  • Customer Stories
  • Documentation
  • Blog
  • All Services
  • System Status
  • Marketplace
    • Featured
    • Infrastructure & Network
    • Data Platform
    • AI for business
    • Security
    • DevOps tools
    • Serverless
    • Monitoring & Resources
  • 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
    • Price calculator
    • Pricing plans
  • Customer Stories
  • Documentation
  • Blog
© 2026 Direct Cursus Technology L.L.C.
Tutorials
    • All tutorials
      • Deploying a web application using the Java Servlet API
      • Developing a custom integration in API Gateway
      • URL shortener
      • Developing CRUD APIs for a movie service
      • Creating an interactive serverless application using WebSocket
      • Working with an API gateway via WebSocket
      • Creating a Node.js function using TypeScript
      • Running a containerized app in Serverless Containers
      • Connecting to YDB from a Cloud Functions Python function
      • Connecting to a YDB database from a Cloud Functions Node.js function
      • Setting up a Yandex Managed Service for PostgreSQL connection from a container in Serverless Containers
      • Deploying a web app with JWT authorization in API Gateway and authentication in Firebase
      • Developing functions in Functions Framework and deploying them to Yandex Serverless Containers
      • Canary release of a function in Cloud Functions
      • Interactive debugging of functions in Cloud Functions
      • Creating a Yandex Cloud Postbox address and a domain ownership check with Terraform
      • Configuring Postfix to send emails via Yandex Cloud Postbox

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. Serverless-based backend
  3. Connecting to YDB from a Cloud Functions Python function

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 April 13, 2026
  • 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.

Use a metadata service to authorize your function with an associated service account in YDB.

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 database connection parameters are provided to the application using 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 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 create or select a folder for your infrastructure on the cloud page.

Learn more about clouds and folders here.

Required paid resourcesRequired paid resources

The infrastructure support cost for this tutorial includes:

  • Fee for using the function (see Yandex Cloud Functions pricing).
  • Fee for running queries against 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. Go to Identity and Access Management.

  3. Click Create service account.

  4. Enter a name for the service account, e.g., sa-function. Follow these naming requirements:

    • Length: between 3 and 63 characters.
    • It can only 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. Go to Managed Service for YDB.

  3. Click Create a database.

  4. Name the database. Follow these naming requirements:

    • Length: between 3 and 63 characters.
    • It can only 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 database 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 database name.

  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 where you want to create a function.

  2. Go to Cloud Functions.

  3. Click Create function.

  4. Enter a name and description for the function. Follow these naming requirements:

    • Length: between 3 and 63 characters.
    • It can only 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 test results.

    If your database is connected and successfully queried, 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 database.
  2. Delete the function.

Was the article helpful?

Previous
Running a containerized app in Serverless Containers
Next
Connecting to a YDB database from a Cloud Functions Node.js function
© 2026 Direct Cursus Technology L.L.C.