Authentication using environment variables

Note

The article is being updated.

When using this method, the authentication mode and its parameters are defined by the environment that an application is run in, as described here.

By setting one of the following environment variables, you can control the authentication method:

  • YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS=<path/to/sa_key_file>: Use a service account file in Yandex.Cloud.
  • YDB_ANONYMOUS_CREDENTIALS="1": Use anonymous authentication. Relevant for testing against a Docker container with YDB
  • YDB_METADATA_CREDENTIALS="1": Use the metadata service inside Yandex.Cloud (a Yandex function or a VM).
  • YDB_ACCESS_TOKEN_CREDENTIALS=<access_token>: Use token-based authentication.

Below are examples of the code for authentication using environment variables in different YDB SDKs.

Go

Java

  1. package main
  2. import (
  3. "context"
  4. "os"
  5. environ "github.com/ydb-platform/ydb-go-sdk-auth-environ"
  6. "github.com/ydb-platform/ydb-go-sdk/v3"
  7. )
  8. func main() {
  9. ctx, cancel := context.WithCancel(context.Background())
  10. defer cancel()
  11. db, err := ydb.Open(
  12. ctx,
  13. os.Getenv("YDB_CONNECTION_STRING"),
  14. environ.WithEnvironCredentials(ctx),
  15. )
  16. if err != nil {
  17. panic(err)
  18. }
  19. defer func() {
  20. _ = db.Close(ctx)
  21. }()
  22. }

Using environment variables - 图1

  1. public void work(String connectionString) {
  2. AuthProvider authProvider = CloudAuthHelper.getAuthProviderFromEnviron();
  3. GrpcTransport transport = GrpcTransport.forConnectionString(connectionString)
  4. .withAuthProvider(authProvider)
  5. .build();
  6. TableClient tableClient = TableClient
  7. .newClient(GrpcTableRpc.ownTransport(transport))
  8. .build());
  9. doWork(tableClient);
  10. tableClient.close();
  11. }

Using environment variables - 图2