Connecting to a Yandex Managed Service for YDB database from a Cloud Functions function in Node.js
Note
This guide is intended for Linux users. On Windows, you can follow it in WSL
You will create a function with a Node.js apptcs
command to compile it.
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 set up a connection to a YDB database:
- Prepare your cloud.
- Prepare the environment.
- Create a service account.
- Create an authorized key.
- Create a YDB database.
- Create a function.
- Test the function.
If you no longer need the resources you created, delete them.
Prepare your cloud
Sign up for Yandex Cloud and create a billing account:
- Go to the management console
and log in to Yandex Cloud or create an account if you do not have one yet. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
If you have an active billing account, you can go to the cloud page
Learn more about clouds and folders.
Required 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 Yandex Managed Service for YDB pricing).
Prepare the environment
-
Clone the examples repository
using Git:git clone https://github.com/yandex-cloud/examples.git
-
Install and initialize the Yandex Cloud CLI.
-
Go to the project root directory:
cd ~/examples/serverless/functions/YDB-connect-from-serverless-function
Make sure to run all further commands in this directory.
-
Install the jq
utility:sudo apt-get install jq
-
Install Node.js
:curl --fail --silent --show-error --location https://deb.nodesource.com/setup_current.x | sudo -E bash - \ sudo apt-get install -y nodejs
-
Install the dependencies:
npm install
Result:
up to date, audited 269 packages in 1s 29 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
Create a service account
- In the management console
, select the folder where you want to create a service account. - In the list of services, select Identity and Access Management.
- Click Create service account.
- Enter a name for the service account:
sa-function
. - Click Add role and select
editor
. - Click Create.
-
Create a service account:
yc iam service-account create --name sa-function
Result:
id: aje028do8n9r******** folder_id: b1g681qpemb4******** created_at: "2023-08-23T06:24:49.759304161Z" name: sa-function
-
Assign the
editor
role to the service account:yc resource-manager folder add-access-binding <folder_ID> \ --role editor \ --subject serviceAccount:<service_account_ID>
Result:
...1s...done (4s) effective_deltas: - action: ADD access_binding: role_id: viewer subject: id: aje028do8n9r******** type: serviceAccount
For more information about the commands, see the CLI reference.
If you don't have Terraform, install it and configure the Yandex Cloud provider.
-
In the configuration file, describe the service account parameters:
resource "yandex_iam_service_account" "sa" { name = "sa-function" }
For more information about the resources you can create with Terraform, see the provider documentation
. -
Make sure the configuration files are correct.
-
In the command line, go to the directory where you created the configuration file.
-
Run a check using this command:
terraform plan
If the configuration is described correctly, the terminal will display a list of created resources and their parameters. If the configuration contains any errors, Terraform will point them out.
-
-
Deploy cloud resources.
-
If the configuration does not contain any errors, run this command:
terraform apply
-
Confirm creating the resources: type
yes
in the terminal and press Enter.
-
To create a service account and assign it a role, use the create and setAccessBindings methods for the ServiceAccount resource.
Create an authorized key
-
In the management console
, select the folder the service account belongs to. -
In the list of services, select Identity and Access Management.
-
In the left-hand panel, select
Service accounts. -
In the list that opens, select the
sa-function
service account. -
Click Create new key in the top panel.
-
Select Create authorized key.
-
Select the encryption algorithm.
-
Enter a description for the authorized key so you can easily find it in the management console.
-
Save both the public and private parts of the authorized key to the
examples/serverless/functions/YDB-connect-from-serverless-function/service_account_key_file.json
file:{ "service_account_id": "<sa-function_service_account_ID>", "key_algorithm": "RSA_2048", "public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n", "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" }
Run this command:
yc iam key create --service-account-name sa-function -o service_account_key_file.json
For more information about the yc iam key create
command, see the CLI reference.
If successful, the private part of the authorized key (privateKey
) and the ID of its public part (id
) will be written to the service_account_key_file.json
file.
-
In the configuration file, describe the authorized key parameters:
resource "yandex_iam_service_account_key" "sa-auth-key" { service_account_id = "<sa-function_service_account_ID>" key_algorithm = "RSA_2048" }
For more information about the resources you can create with Terraform, see the provider documentation
. -
Make sure the configuration files are correct.
-
In the command line, go to the directory where you created the configuration file.
-
Run a check using this command:
terraform plan
If the configuration is described correctly, the terminal will display a list of created resources and their parameters. If the configuration contains any errors, Terraform will point them out.
-
-
Deploy cloud resources.
-
If the configuration does not contain any errors, run this command:
terraform apply
-
Confirm creating the resources: type
yes
in the terminal and press Enter.
-
Create a YDB database
-
In the management console
, select the folder where you want to create a database. -
In the list of services, select Managed Service for YDB.
-
Click Create a database.
-
Name the database. The naming requirements are as follows:
- The name must be from 3 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter and the last character cannot be a hyphen.
-
Under Database type, select
Serverless
. -
Click Create a database.
Wait for the DB to start. When being created, a database has the
Provisioning
status. Once it is ready for use, its status will change toRunning
. -
Click the name of the database you created.
-
Save the value of the Endpoint field from the Connection section. You will need it at the next step.
Create a function
Note
Before creating a function, make sure the .env
file and the create-func.sh
and create-func-ver.sh
files from the deploy
directory have the LF
(line feed) character set.
-
Go to the project root directory:
cd ~/examples/serverless/functions/YDB-connect-from-serverless-function
-
Edit the
.env
file:ENDPOINT
: First part of the previously saved Endpoint field value (preceding/?database=
), e.g.,grpcs://ydb.serverless.yandexcloud.net:2135
.DATABASE
: Second part of the previously saved Endpoint field value (following/?database=
), e.g.,/ru-central1/r1gra875baom********/g5n22e7ejfr1********
.FUNCTION_NAME
: Function name, which isfunc-test-ydb
.FOLDER_ID
: Folder ID.SERVICE_ACCOUNT_ID
:sa-function
service account ID.
-
Create a function:
./deploy/create-func.sh
This script creates a new function in your folder and makes it public.
-
Create a function version:
./deploy/create-func-ver.sh
Result:
npx tsc --build tsconfig.json rm: Cannot delete '../build/func.zip': File or folder does not exist. adding: queries/ (stored 0%) adding: queries/clients-table.js (deflated 57%) adding: queries/helpers.js.map (deflated 43%) adding: queries/helpers.js (deflated 48%) adding: queries/clients-table.js.map (deflated 59%) adding: index.js (deflated 49%) adding: index.js.map (deflated 56%) adding: database.js.map (deflated 62%) adding: index-local.js (deflated 42%) adding: package.json (deflated 55%) adding: database.js (deflated 60%) adding: index-local.js.map (deflated 43%) yc function version create func-test-ydb done (27s) id: abcd2d363b4b******** function_id: efghm9el0ja9******** created_at: "2023-08-15T07:41:07.591Z" runtime: nodejs16 entrypoint: index.handler resources: memory: "268435456" execution_timeout: 5s service_account_id: hijk3hlu8gqe******** image_size: "33497088" status: ACTIVE tags: - $latest log_group_id: lmnoivbe341g******** environment: DATABASE: /ru-central1/b1gia87mbaom********/etnilt3o6v9e******** ENDPOINT: grpcs://ydb.serverless.yandexcloud.net:2135 log_options: folder_id: pqrs81qpemb********
Test the function
-
In the management console
, select the folder containing the function. -
In the list of services, select Cloud Functions.
-
Select the
func-test-ydb
function. -
Go to the Overview tab.
-
In the Link to invoke field, click the link.
-
In your browser address bar, add the
api_key
parameter to the link, e.g.,?api_key=b95
:https://functions.yandexcloud.net/efghm9el0ja9********?api_key=b95
-
A successful DB connection will create a table named
b95
with a single record added to it. A message in JSON format will appear on the page, e.g.:{ "info": "b95 table created, one record inserted" }
How to delete the resources you created
To stop paying for the resources you created: