All Products
Search
Document Center

Tablestore:Use temporary access credentials obtained from STS to access Tablestore

Last Updated:Apr 21, 2025

You can generate temporary access credentials by using Security Token Service (STS) to allow a Resource Access Management (RAM) user to access your Tablestore resources within the validity period of the temporary access credentials. This way, you do not need to share your AccessKey pair. After the validity period of temporary access credentials ends, the temporary access credentials automatically become invalid. This ensures flexible and secure access to your Tablestore resources.

Background information

A RAM role is a virtual identity to which permissions to access specific resources can be granted. Compared with a RAM user, a RAM role does not have permanent identity credentials, such as a logon password or an AccessKey pair. A RAM role can be used only if the role is assumed by a trusted entity. After a RAM role is assumed by a trusted entity, the trusted entity can obtain an STS token and use the STS token to access Tablestore as the RAM role.

A RAM role whose trusted entity is an Alibaba Cloud account is used to perform cross-account access and temporary authorization. This topic describes how to use temporary access credentials obtained from STS to initiate a request to access Tablestore resources. In the examples in this topic, a RAM user assumes a RAM role that belongs to the same Alibaba Cloud account.

Procedure

To use temporary access credentials obtained from STS to access Tablestore, create a RAM role to be assumed by a RAM user. The RAM role must have the permissions to access Tablestore. Next, create a RAM user that assumes the RAM role to obtain temporary access credentials from STS. Then, use the temporary access credentials obtained from STS to initiate a request to access Tablestore resources.

Step 1: Create a RAM role

  1. Log on to the RAM console by using your Alibaba Cloud account or a RAM user who has administrative rights.

  2. In the left-side navigation pane, choose Identities > Roles. The Roles page is displayed.

  3. Click Create Role, configure information of the trusted entity, and click OK.

    Parameter

    Sample value

    Principal Type

    Cloud Account

    Principal Name

    Current Account

  4. In the Create Role dialog box, set Role Name to RamTablestore and click OK.

To obtain temporary access credentials from STS, you must specify the Alibaba Cloud Resource Name (ARN) of the RAM role. To obtain the ARN of a RAM role, perform the following steps: Click the name of the RAM role in the RAM role list to go to the role details page. Then, find and copy the ARN in the Basic Information section of the page that appears.

image

Step 2: Grant the RAM role the permissions to access Tablestore

Use the default policy

In this example, the AliyunOTSFullAccess policy is attached to the RAM role to grant the RAM role the permissions to access Tablestore.

Note

The AliyunOTSFullAccess policy contains full access permissions on Tablestore. You can also attach the following policies to the RAM role to grant specific permissions to the RAM role based on your business requirements:

  • To grant read-only access to Tablestore, attach the AliyunOTSReadOnlyAccess policy to the RAM role.

  • To grant write-only access to Tablestore, attach the AliyunOTSWriteOnlyAccess policy to the RAM role.

  1. In the left-side navigation pane, choose Identities > Roles.

  2. On the Roles page, find the RAM role that you want to manage.

  3. Click the name of the RAM role to go to the RAM role details page. On the page that appears, click Grant Permission on the Permissions tab. Alternatively, you can click Grant Permission in the Actions column of the RAM role.

  4. In the Policy section of the Grant Permission panel, search for and select AliyunOTSFullAccess.

  5. Click Grant permissions.

Use a custom policy

  1. Create a custom policy.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, click the JSON tab, write script in the policy document, and then click OK.

      The following sample script allows the RAM role to access a specific instance. You can specify a custom policy script based on your business requirements. For example, you can grant the RAM role the permissions to access a table or call an API operation. You can also grant the RAM role the permissions to access Tablestore only from a specific IP address or before a specific point in time. For more information about RAM policies, see Create a custom policy.
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "ots:*",
            "Resource": "acs:ots:*:*:instance/your_instance_name*"
          }
        ]
      }
    4. In the Create Policy dialog box, enter a policy name, such as TestRAMPolicy, and click OK.

  1. Attach the custom policy to the RAM role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, find the RAM role that you want to manage.

    3. Click the name of the RAM role to go to the RAM role details page. On the page that appears, click Grant Permission on the Permissions tab. Alternatively, you can click Grant Permission in the Actions column of the RAM role.

    4. In the Policy section of the Grant Permission panel, search for and select the custom policy you created.

    5. Click Grant permissions.

You can click the role name in the RAM role list to go to the role details page. On the Permissions tab, you can view the policies that are attached to the RAM role.

image

Step 3: Create a RAM user

Create a RAM user to assume the RAM role.

  1. Log on to the RAM console by using your Alibaba Cloud account or a RAM user who has administrator privileges.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. In the User Account Information section of the Create User page, configure the following parameters:

    • Logon Name: The logon name can be up to 64 characters in length and can contain letters, digits, periods (.), hyphens (-), and underscores (_).

    • Display Name: The display name can be up to 128 characters in length.

    • Tag: Click edit and enter the tag key and tag value. You can add one or more tags to the RAM user. This allows you to manage the RAM user based on the tags.

    Note

    You can click Add User to create multiple RAM users at the same time.

  5. In the Access Mode section, select Using permanent AccessKey to access and click OK.

    Note

    If you want to log on to and access the Alibaba Cloud Management Console as a RAM user, select Console Access.

  6. In the Actions column, click Copy to save the information about the RAM user. You can separately copy the AccessKey ID and AccessKey secret.

    Important

    An AccessKey secret of a RAM user is displayed only when you create the AccessKey pair. After the Create User page is closed, you cannot query the AccessKey secret. Record and store your AccessKey secret in a secure location.

Step 4: Grant the RAM user the AssumeRole permission

The AssumeRole permission is required for a RAM user to assume a RAM role.

  1. In the left-side navigation pane, choose Identities > Users.

  2. On the Users page, find the RAM user that you want to manage.

  3. Click the name of the RAM user to go to the RAM user details page. On the page that appears, click Grant Permission on the Permissions tab. Alternatively, you can click Add Permissions in the Actions column of the RAM user.

  4. In the Policy section of the Grant Permission panel, search for and select AliyunSTSAssumeRoleAccess.

  5. Click Grant permissions.

Step 5: Assume the RAM role as the RAM user to obtain temporary access credentials from STS

Before you access Tablestore resources, you must assume the RAM role as the RAM user to obtain temporary access credentials from STS. Temporary access credentials are valid within the specified validity period. This section uses Java as an example to introduce specific operations.

You can also obtain temporary access credentials by calling the AssumeRole operation in OpenAPI Explorer.

Preparations

Add the following dependency to the Maven project:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>sts20150401</artifactId>
    <version>1.1.6</version>
</dependency>

Sample code

The following sample code provides an example on how to obtain temporary access credentials from STS by assuming a RAM role as a RAM user and display the temporary access credentials in the Tablestore console. In this example, the validity period of the temporary access credentials is 1 hour.

Before you run the code, save the AccessKey pair of the RAM user and the ARN of the RAM role to the system environment variables. For more information, see Configure environment variables.
For information about STS endpoints, see Endpoints.
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.*;

public class AssumeRoleSample {
    public static com.aliyun.sts20150401.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following sample code is provided only for reference. 
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the STS endpoint.
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.sts20150401.Client(config);
    }

    public static void main(String[] args) throws Exception {
        com.aliyun.sts20150401.Client client = AssumeRoleSample.createClient();
        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
                .setDurationSeconds(3600L)
                // Required. Make sure that the TABLESTORE_STS_ROLE_ARN environment variable is configured. The environment variable specifies the ARN of the RAM role. 
                .setRoleArn(System.getenv("TABLESTORE_STS_ROLE_ARN"))
                // Required. Specify the session name for the RAM role to distinguish different tokens. 
                .setRoleSessionName("RAMTablestore");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Obtain temporary access credentials from STS and display the temporary access credentials. Store the temporary access credentials in a secure location. 
            AssumeRoleResponse response = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
            System.out.println("Expiration: " + response.getBody().getCredentials().getExpiration());
            System.out.println("Access Key Id: " + response.getBody().getCredentials().getAccessKeyId());
            System.out.println("Access Key Secret: " + response.getBody().getCredentials().getAccessKeySecret());
            System.out.println("Security Token: " + response.getBody().getCredentials().getSecurityToken());
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only. 
            // Display error messages.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only. 
            // Display error messages.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

For information about how to use STS SDKs for other programming languages to obtain temporary access credentials and the specific sample code, see STS SDK overview.

Step 6: Use temporary access credentials obtained from STS to access Tablestore

Preparations

  1. Create an instance and a data table in the Tablestore console.

  2. Obtain the name, endpoint, and region ID of the instance. For more information, see Endpoints and Regions.

    Important

    By default, Internet-based access is diabled for a newly created instance. If you want to access resources in an instance over the Internet, you must enable Internet-based access for the instance. For more information, see Solution.

  3. Install the Tablestore SDK for the required programming language.

    Java

    If you use Maven to manage Java projects, add the following dependency to the pom.xml file:

    <dependency>
        <groupId>com.aliyun.openservices</groupId>
        <artifactId>tablestore</artifactId>
        <version>5.17.4</version>
    </dependency>                 

    For more information, see Install Tablestore SDK for Java.

    Go

    Run the go mod init <DIRNAME> command in the project directory to generate the go.mo d file. Then, run the following command to install Tablestore SDK for Go:

    Note

    <DIRNAME> indicates the project directory path. Replace <DIRNAME> with the actual project directory path.

    go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore

    For more information, see Install Tablestore SDK for Go.

    Python

    Run the following command to use pip to install Tablestore SDK for Python:

    sudo pip install tablestore

    For more information, see Install Tablestore SDK for Python.

    Node.js

    Use npm to run the following command to install Tablestore SDK for Node.js:

    npm install tablestore

    For more information, see Install Tablestore SDK for Node.js.

    .NET

    For more information, see Install Tablestore SDK for .NET.

    PHP

    For more information, see Install Tablestore SDK for PHP.

Wide Column model

When you use the Wide Column model, you must use the temporary access credentials obtained from STS to initialize a client for the Wide Column model and initiate a request.

Before you run the code, replace the sample instance information in the code with the actual instance information and save the temporary access credentials obtained from STS to the system environment variables. For more information, see Configure environment variables.
Java
(Recommended) Use a V4 signature

The following sample Java code provides an example on how to use a V4 signature to initialize a client and query the list of data tables in an instance:

import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.*;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

public class InitClientV4 {
    public static void main(String[] args) {
        // Specify the region in which the instance that you want to access resides. Example: cn-hangzhou.
        final String region = "yourRegion";
        // Specify the name of the instance.
        final String instanceName = "yourInstanceName";
        // Specify the endpoint of the instance.
        final String endpoint = "yourEndpoint";
        // Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
        final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");

        // Construct a V4 signature.
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
        CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

        // Initialize a client.
        SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

        /*
        // You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations. 
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds. 
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds. 
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used. 
        SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */

        // Query the list of data tables in the instance and display the list in the Tablestore console.
        ListTableResponse listTableResponse = client.listTable();
        listTableResponse.getTableNames().forEach(System.out::println);

        // Shut down the Tablestore client.
        client.shutdown();
    }
}
Use a V2 signature

The following sample Java code provides an example on how to use a V2 signature to initialize a client and query the list of data tables in an instance:

import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.ListTableResponse;

public class InitClientV2 {
    public static void main(String[] args) {
        // Specify the name of the instance.
        final String instanceName = "yourInstanceName";
        // Specify the endpoint of the instance.
        final String endpoint = "yourEndpoint";
        // Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
        final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");

        // Construct a V2 signature.
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        CredentialsProvider provider = new DefaultCredentialProvider(credentials);

        // Initialize a client.
        SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

        /*
        // You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations. 
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds. 
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds. 
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used. 
        SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */

        // Query the list of data tables in the instance and display the list in the Tablestore console.
        ListTableResponse listTableResponse = client.listTable();
        listTableResponse.getTableNames().forEach(System.out::println);

        // Shut down the Tablestore client.
        client.shutdown();
    }
}
Go

The following sample Go code provides an example on how to initialize a client and query the list of data tables in an instance:

package main

import (
	"fmt"
	"os"
	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

func main() {
	// Specify the name of the instance.
	instanceName := "yourInstanceName"
	// Specify the endpoint of the instance.
	endpoint := "yourEndpoint"
	// Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
	accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
	accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
	securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")

	// Initialize a client.
	client := tablestore.NewClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil)	

	// Query the list of data tables in the instance and display the list in the Tablestore console.
	tables, err := client.ListTable()
    if err != nil {
        fmt.Println("Failed to list table.")
    } else {
        for _, table := range (tables.TableNames) {
            fmt.Println(table)
        }
    }
}
Python

The following sample Python code provides an example on how to initialize a client and query the list of data tables in an instance:

# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient

# Specify the name of the instance.
instance_name = "yourInstanceName"
# Specify the endpoint of the instance.
endpoint = "yourEndpoint"
# Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
sts_token = os.getenv("TABLESTORE_SESSION_TOKEN")

# Initialize a client.
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)

# Query the list of data tables in the instance and display the list in the Tablestore console.
resp = client.list_table()
for table_name in resp:
    print(table_name)
Node.js

The following sample Node.js code provides an example on how to initialize a client and query the list of data tables in an instance:

// In this example, the path is a relative path. Modify the path based on your business requirements. 
var TableStore = require('../index.js');

// Specify the name of the instance.
var instancename = 'yourInstanceName';
// Specify the endpoint of the instance.
var endpoint = 'yourEndpoint';
// Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
var accessKeySecret = process.env.TABLESTORE_ACCESS_KEY_SECRET;
var stsToken = process.env.TABLESTORE_SESSION_TOKEN;

// Initialize a client.
var client = new TableStore.Client({
  accessKeyId: accessKeyId,
  secretAccessKey: accessKeySecret,
  stsToken: stsToken,
  endpoint: endpoint,
  instancename: instancename 
});

// Query the list of data tables in the instance and display the list in the Tablestore console.
client.listTable({}, function (err, data) {
    if (err) {
        console.log('error:', err);
        return;
    }
    console.log('success:', data);
});
PHP

The following sample PHP code provides an example on how to initialize a client and query the list of data tables in an instance:

<?php
// In this example, the path is a relative path. Modify the path based on your business requirements. 
require (__DIR__ . '/../../vendor/autoload.php');

use Aliyun\OTS\OTSClient as OTSClient;

// Specify the name of the instance.
$instanceName = "yourInstanceName";
// Specify the endpoint of the instance.
$endpoint = "yourEndpoint";
// Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
$stsToken = getenv('TABLESTORE_SESSION_TOKEN');


// Initialize a client.
$otsClient = new OTSClient(array(
    'EndPoint' => $endpoint,
    'AccessKeyID' => $accessKeyId,
    'AccessKeySecret' => $accessKeySecret,
    'InstanceName' => $instanceName,
    'StsToken' => $stsToken,
));

// Query the list of data tables in the instance and display the list in the Tablestore console.
$response = $otsClient->listTable (array ());
print json_encode ($response);

TimeSeries model

When you use the TimeSeries model, you must use the temporary access credentials obtained from STS to initialize a client for the TimeSeries model and initiate a request. Only Tablestore SDK for Java, Tablestore SDK for Go, and Tablestore SDK for Python support the TimeSeries model.

Before you run the code, replace the sample instance information in the code with the actual instance information and save the temporary access credentials obtained from STS to the system environment variables. For more information, see Configure environment variables.
Java
(Recommended) Use a V4 signature

The following sample Java code provides an example on how to use a V4 signature to initialize a client and query the list of time series tables in an instance:

import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

public class InitTimeseriesClientV4 {
    public static void main(String[] args) {
        // Specify the region in which the instance that you want to access resides. Example: cn-hangzhou.
        final String region = "yourRegion";
        // Specify the name of the instance.
        final String instanceName = "yourInstanceName";
        // Specify the endpoint of the instance.
        final String endpoint = "yourEndpoint";
        // Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
        final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");

        // Construct a V4 signature.
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
        CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);

        // Initialize a client.
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

        /*
        // You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations. 
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds. 
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds. 
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used. 
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */

        // Query the list of time series tables in the instance and display the list in the Tablestore console.
        ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
        listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);

        // Shut down the TimeSeriesClient.
        client.shutdown();
    }
}
Use a V2 signature

The following sample Java code provides an example on how to use a V2 signature to initialize a client and query the list of time series tables in an instance:

import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;

public class InitTimeseriesClientV2 {
    public static void main(String[] args) {
        // Specify the name of the instance.
        final String instanceName = "yourInstanceName";
        // Specify the endpoint of the instance.
        final String endpoint = "yourEndpoint";
        // Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
        final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
        final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
        final String securityToken = System.getenv("TABLESTORE_SESSION_TOKEN");

        // Construct a V2 signature.
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        CredentialsProvider provider = new DefaultCredentialProvider(credentials);

        // Initialize a client.
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));

        /*
        // You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations. 
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds. 
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds. 
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used. 
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */

        // Query the list of time series tables in the instance and display the list in the Tablestore console.
        ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
        listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);

        // Shut down the TimeSeriesClient.
        client.shutdown();
    }
}
Go

The following sample Go code provides an example on how to initialize a client and query the list of time series tables in an instance:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

func main() {
    // Specify the name of the instance.
    instanceName := "yourInstanceName"
    // Specify the endpoint of the instance.
    endpoint := "yourEndpoint"
    // Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
    accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
    securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")

    // Initialize a client.
    client := tablestore.NewTimeseriesClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil, nil)    

    // Query the list of time series tables in the instance and display the list in the Tablestore console.
    timeseriesTables, err := client.ListTimeseriesTable()
    if err != nil {
        fmt.Println("Failed to list table.")
    } else {
        for _, timeseriesTablesMeta := range (timeseriesTables.GetTimeseriesTableMeta()) {
            fmt.Println(timeseriesTablesMeta.GetTimeseriesTableName())
        }
    }
}

Python

The following sample Python code provides an example on how to initialize a client and query the list of time series tables in an instance:

# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient

# Specify the name of the instance.
instance_name = "yourInstanceName"
# Specify the endpoint of the instance.
endpoint = "yourEndpoint"
# Obtain the temporary AccessKey ID, temporary AccessKey secret, and security token from the environment variables.
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
sts_token = os.getenv("TABLESTORE_SESSION_TOKEN")

# Initialize a client.
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)

# Query the list of time series tables in the instance and display the list in the Tablestore console.
response = client.list_timeseries_table()
for tableMeta in response:
    print(tableMeta.timeseries_table_name)

Configure environment variables

If you save access credentials to the code, information leaks may occur. We recommend that you save access credentials to system environment variables. Run the following code:

Windows

# Specify the AccessKey ID of the RAM user.
setx ALIBABA_CLOUD_ACCESS_KEY_ID your_access_key_id /m
# Specify the AccessKey secret of the RAM user.
setx ALIBABA_CLOUD_ACCESS_KEY_SECRET your_access_key_secret /m
# Specify the ARN of the RAM role.
setx TABLESTORE_STS_ROLE_ARN your_ram_role_arn /m
# Specify the temporary AccessKey ID obtained from STS.
setx TABLESTORE_ACCESS_KEY_ID your_sts_access_key_id /m
# Specify the temporary AccessKey secret obtained from STS.
setx TABLESTORE_ACCESS_KEY_SECRET your_sts_access_key_secret /m
# Specify the security token obtained from STS.
setx TABLESTORE_SESSION_TOKEN your_sts_token /m

macOS/Linux/Unix

# Specify the AccessKey ID of the RAM user.
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
# Specify the AccessKey secret of the RAM user.
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
# Specify the ARN of the RAM role.
export TABLESTORE_STS_ROLE_ARN=your_ram_role_arn
# Specify the temporary AccessKey ID obtained from STS.
export TABLESTORE_ACCESS_KEY_ID=your_sts_access_key_id
# Specify the temporary AccessKey secret obtained from STS.
export TABLESTORE_ACCESS_KEY_SECRET=your_sts_access_key_secret
# Specify the security token obtained from STS.
export TABLESTORE_SESSION_TOKEN=your_sts_token

FAQ

Q: What do I do if the "You are not authorized to do this action. You should be authorized by RAM" error message is returned?

When you assume the RAM role by using the RAM user to obtain temporary access credentials, you must use the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user, not the AccessKey pair of the Alibaba Cloud account.

Q: What do I do if the "The Min/Max value of DurationSeconds is 15min/1hr" error message is returned?

This error message is returned when the validity period of the temporary access credentials does not fall within the valid range. Specify the validity period based on the following rules:

  • If the default maximum session duration of the role (3,600 seconds) is used, the minimum validity period is 900 seconds and the maximum validity period is 3,600 seconds for the temporary access credentials.

  • If a custom maximum session duration is specified for the role, the minimum validity period is 900 seconds and the maximum validity period is the same as the specified maximum session duration. The maximum session duration of the role ranges from 3,600 to 43,200 seconds.

You can view the maximum session duration for the role in the RAM console.

Q: What do I do if the "The security token you provided is invalid" error message is returned?

Make sure that you specify the complete security token obtained from STS and check whether environment variables are correctly configured.

Q: Can I obtain multiple sets of temporary access credentials at the same time?

Yes. You can obtain multiple sets of temporary access credentials at the same time. You can send a request to STS to obtain a set of temporary access credentials. If you want to obtain multiple sets of temporary access credentials from STS, send multiple requests to STS. You can simultaneously use multiple sets of temporary access credentials within the validity periods of the temporary access credentials.

Q: What do I do if the "Request denied by instance ACL policies" error message is returned when I use a Tablestore SDK to access Tablestore?

This error indicates that network type that is used by your client to access resources in the Tablestore instance is not supported by the instance. On the Network Management tab of the Instance Management page, select the network type that is used by your client for the Allowed Network Type parameter. For more information, see What do I do if the "Request denied by instance ACL policies" exception occurs when I use a Tablestore SDK to access Tablestore?