All Products
Search
Document Center

Tablestore:Use STS temporary credentials to access Tablestore

Last Updated:Jun 20, 2026

You can use Security Token Service (STS) to issue a temporary access credential to another user. The user can use this credential to access Tablestore resources within the credential's validity period. Temporary credentials do not expose your long-term keys. After expiration, they automatically become invalid, making access to your Tablestore resources more flexible and secure.

Background information

A RAM role is a virtual user that can be granted permissions to access specific resources. Unlike a RAM user, a RAM role has no permanent identity credentials (such as a logon password or AccessKey pair). A trusted entity (such as a RAM user) must assume the role. After successful assumption, the trusted entity receives temporary identity credentials for the RAM role—specifically, a Security Token Service token (STS Token)—and can use this token to access Tablestore as the RAM role.

RAM roles for Alibaba Cloud accounts primarily address cross-account access and temporary authorization scenarios. This topic uses an example where a RAM user within the same account assumes a RAM role to demonstrate how to use STS temporary credentials to access Tablestore resources.

Procedure

To use STS temporary credentials to access Tablestore, first create a RAM role to be assumed and grant it permissions to access Tablestore. Next, create a RAM user to assume the RAM role and obtain STS temporary credentials. Finally, use these credentials to send requests to access Tablestore resources.

Step 1: Create a RAM role

  1. Log on to the Resource Access Management (RAM) console using your Alibaba Cloud account (main account) or as a RAM administrator.

  2. In the navigation pane on the left, choose Identities > Roles to go to the Roles page.

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

    Parameter

    Example value

    Trusted entity type

    Alibaba Cloud account

    Trusted entity name

    Current Alibaba Cloud account

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

When using STS to obtain temporary credentials, you must specify the ARN of the RAM role. You can find and copy the ARN in the Basic Information section of the role details page.

The ARN format for this role is acs:ram::<Alibaba Cloud account ID>:role/ramtablestore. Click the Copy button next to the ARN to obtain it.

Step 2: Grant accessTablestorepermissions

Use a default policy

Grant the RAM role permissions to access Tablestore using the AliyunOTSFullAccess policy.

Note

The AliyunOTSFullAccess policy grants full access to Tablestore. You can also choose one of the following options:

  • For read-only permission, grant the RAM role the AliyunOTSReadOnlyAccess policy.

  • For write-only permission, grant the RAM role the AliyunOTSWriteOnlyAccess policy.

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

  2. On the Roles page, find the target RAM role.

  3. Click Attach Policy next to the RAM role, or click the role name to go to its details page and click Grant Permission in the Permissions section.

  4. In the Grant Permission panel, in the Access Policy section, search for AliyunOTSFullAccess and select it.

  5. Click Confirm New Authorization.

Use a custom policy

  1. Create a custom policy.

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

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, click Script Editor, enter the script in the input box, and click OK.

      The following sample script grants permissions to access a single instance. Customize the policy script as needed—for example, to control permissions at the table or API level, or based on conditions such as IP address or access time. For more information about RAM policies, see Custom RAM policies.
      {
        "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. Grant the custom policy to the RAM role.

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

    2. On the Roles page, find the target RAM role.

    3. Click Attach Policy next to the RAM role, or click the role name to go to its details page and click Grant Permission in the Permissions section.

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

    5. Click Confirm.

You can view the granted policies on the Permissions tab of the role details page.

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 that has administrative permissions.

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

  3. On the Users page, click Create User.

  4. On the Create User page, in the User Account Information section, configure the user's basic information:

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

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

    • Tag: Click the edit icon and enter a tag key and a tag value. Adding a tag helps you find and manage the RAM user.

    Note

    You can click Add User to create multiple RAM users in a batch.

  5. In the Access Mode section, select Programmatic Access, and then click OK.

    Note

    To allow the RAM user to log on to the Alibaba Cloud Management Console, select Console Access.

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

    Important

    The AccessKey secret is shown only once upon creation and cannot be retrieved later. Store it in a secure location immediately.

Step 4: Grant the RAM user permission to call AssumeRole

To assume a RAM role, the RAM user must have permission to call AssumeRole.

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

  2. On the Users page, find the target RAM user.

  3. Click Add Permissions next to the RAM user, or click the user name to go to its details page and click Grant Permission on the Permission Management tab.

  4. In the Grant Permission panel's access policy section, search for AliyunSTSAssumeRoleAccess and select it.

  5. Click Confirm.

Step 5: Use the RAM user to assume the RAM role and obtain temporary credentials

Before accessing resources, use the RAM user to assume the RAM role and obtain temporary credentials. These credentials are valid only during their validity period. This example uses Java.

You can also directly call the AssumeRole operation in the OpenAPI Explorer to obtain temporary credentials.

Preparations

  1. Add the following dependency to your Maven project.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>sts20150401</artifactId>
        <version>1.1.6</version>
    </dependency>
  2. Configure environment variables. After configuration is complete, restart or refresh your compilation and runtime environment, including IDE, command-line interface, other desktop applications, and background services to ensure that the latest system environment variables are successfully loaded.

    Linux
    1. Run the following commands in the command-line interface to append environment variable settings to the ~/.bashrc file.

      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bashrc
    2. Run the following command to allow the changes to take effect:

      source ~/.bashrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
      echo $TABLESTORE_STS_ROLE_ARN
    macOS
    1. Run the following command in the terminal to check the default Shell type.

      echo $SHELL
    2. Perform operations based on the default Shell type.

      Zsh
      1. Run the following commands to append environment variable settings to the ~/.zshrc file.

        echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.zshrc
      2. Run the following command to allow the changes to take effect:

        source ~/.zshrc
      3. Run the following commands to check whether the environment variables take effect:

        echo $ALIBABA_CLOUD_ACCESS_KEY_ID
        echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
        echo $TABLESTORE_STS_ROLE_ARN
      Bash
      1. Run the following commands to append environment variable settings to the ~/.bash_profile file.

        echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bash_profile
      2. Run the following command to allow the changes to take effect:

        source ~/.bash_profile
      3. Run the following commands to check whether the environment variables take effect:

        echo $ALIBABA_CLOUD_ACCESS_KEY_ID
        echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
        echo $TABLESTORE_STS_ROLE_ARN
    Windows
    CMD
    1. Run the following commands in CMD to set environment variables.

      setx ALIBABA_CLOUD_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx ALIBABA_CLOUD_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      setx TABLESTORE_STS_ROLE_ARN "YOUR_RAM_ROLE_ARN"
    2. After restarting CMD, run the following commands to check whether the environment variables take effect:

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
      echo %TABLESTORE_STS_ROLE_ARN%
    PowerShell
    1. Run the following command in PowerShell:

      [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_STS_ROLE_ARN", "YOUR_RAM_ROLE_ARN", [EnvironmentVariableTarget]::User)
    2. Run the following commands to check whether the environment variables take effect:

      [Environment]::GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_STS_ROLE_ARN", [EnvironmentVariableTarget]::User)

Sample code

The following sample code uses a RAM user to assume a RAM role, obtains STS temporary credentials, and prints them to the console. The credentials are valid for one hour.

For a list of 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 {
        // Leaking AccessKey credentials in source code may compromise all resources under your account. Use this sample code for reference only.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Ensure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Ensure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Endpoint for the STS service
        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()
                // Validity period of the temporary credential, in seconds. Minimum is 900. Maximum depends on the role's maximum session duration (range: 3600–43200 seconds; default: 3600).
                .setDurationSeconds(3600L)
                // Required. Ensure the TABLESTORE_STS_ROLE_ARN environment variable (the RAM role ARN) is set.
                .setRoleArn(System.getenv("TABLESTORE_STS_ROLE_ARN"))
                // Required. A custom role session name to distinguish tokens.
                .setRoleSessionName("RAMTablestore");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // Obtain and print STS temporary credentials. Store them securely.
            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) {
            // Print errors for demonstration only. Handle exceptions carefully in production code. Never ignore them.
            // Error message
            System.out.println(error.getMessage());
            // Diagnostic link
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Print errors for demonstration only. Handle exceptions carefully in production code. Never ignore them.
            // Error message
            System.out.println(error.getMessage());
            // Diagnostic link
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

For STS SDKs and code samples in other languages, see Overview of STS SDKs.

Step 6: Access using temporary access credentialsTablestore

Preparations

  1. Create an instance and data tables in the Tablestore console.

  2. Obtain the instance name, instance endpoint, and region ID.

    Important

    New instances do not enable public network access by default. If you need public network access, enable public network access for the instance.

  3. Configure environment variables. After configuration is complete, restart or refresh your compilation and runtime environment, including IDE, command-line interface, other desktop applications, and background services to ensure that the latest system environment variables are successfully loaded.

    Linux
    1. Run the following commands in the command-line interface to append environment variable settings to the ~/.bashrc file.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bashrc
      echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bashrc
    2. Run the following command to allow the changes to take effect:

      source ~/.bashrc
    3. Run the following commands to check whether the environment variables take effect:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET
      echo $TABLESTORE_SESSION_TOKEN
    macOS
    1. Run the following command in the terminal to check the default Shell type.

      echo $SHELL
    2. Perform operations based on the default Shell type.

      Zsh
      1. Run the following commands to append environment variable settings to the ~/.zshrc file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.zshrc
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.zshrc
      2. Run the following command to allow the changes to take effect:

        source ~/.zshrc
      3. Run the following commands to check whether the environment variables take effect:

        echo $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN
      Bash
      1. Run the following commands to append environment variable settings to the ~/.bash_profile file.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bash_profile
      2. Run the following command to allow the changes to take effect:

        source ~/.bash_profile
      3. Run the following commands to check whether the environment variables take effect:

        echo $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN
    Windows
    CMD
    1. Run the following commands in CMD to set environment variables.

      setx TABLESTORE_ACCESS_KEY_ID "YOUR_STS_ACCESS_KEY_ID"
      setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_STS_ACCESS_KEY_SECRET"
      setx TABLESTORE_SESSION_TOKEN "YOUR_STS_TOKEN"
    2. After restarting CMD, run the following commands to check whether the environment variables take effect:

      echo %TABLESTORE_ACCESS_KEY_ID%
      echo %TABLESTORE_ACCESS_KEY_SECRET%
      echo %TABLESTORE_SESSION_TOKEN%
    PowerShell
    1. Run the following command in PowerShell:

      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_STS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_STS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", "YOUR_STS_TOKEN", [EnvironmentVariableTarget]::User)
    2. Run the following commands to check whether the environment variables take effect:

      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", [EnvironmentVariableTarget]::User)
  4. Install the Tablestore SDK for your programming language.

    Java

    If you use Maven, add the following dependency to your project's 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

    Run the following command to install the Tablestore SDK for Node.js:

    npm install tablestore

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

    .NET

    For details, see Install Tablestore SDK for .NET.

    PHP

    For details, see Install Tablestore SDK for PHP.

Wide table model

When using the wide table model, initialize the wide table client with STS temporary credentials and send requests.

Java
V4 signature (recommended)

The following Java sample code initializes a client using V4 signature and lists all table names in the 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) {
        // Replace yourRegion with your instance region, such as cn-hangzhou
        final String region = "yourRegion";
        // Replace yourInstanceName with your instance name
        final String instanceName = "yourInstanceName";
        // Replace yourEndpoint with your instance endpoint
        final String endpoint = "yourEndpoint";
        // Get STS credentials from 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");
        // Build V4 signature
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
        CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
        // Initialize Tablestore client
        SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
        /*
        // Customize ClientConfiguration if needed. Examples:
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
        SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */
        // List and print table names
        ListTableResponse listTableResponse = client.listTable();
        listTableResponse.getTableNames().forEach(System.out::println);
        // Shut down Tablestore client
        client.shutdown();
    }
}
V2 signature

The following Java sample code initializes a client using V2 signature and lists all table names in the 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) {
        // Replace yourInstanceName with your instance name
        final String instanceName = "yourInstanceName";
        // Replace yourEndpoint with your instance endpoint
        final String endpoint = "yourEndpoint";
        // Get STS credentials from 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");
        // Build V2 signature
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        CredentialsProvider provider = new DefaultCredentialProvider(credentials);
        // Initialize Tablestore client
        SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
        /*
        // Customize ClientConfiguration if needed. Examples:
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
        SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */
        // List and print table names
        ListTableResponse listTableResponse = client.listTable();
        listTableResponse.getTableNames().forEach(System.out::println);
        // Shut down Tablestore client
        client.shutdown();
    }
}
Go

The following Go sample code initializes a client and lists all table names in the instance.

package main
import (
	"fmt"
	"os"
	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
	// Replace yourInstanceName with your instance name
	instanceName := "yourInstanceName"
	// Replace yourEndpoint with your instance endpoint
	endpoint := "yourEndpoint"
	// Get STS credentials from environment variables
	accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
	accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
	securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")
	// Initialize Tablestore client
	client := tablestore.NewClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil)	
	// List and print table names
	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 Python sample code initializes a client and lists all table names in the instance.

# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with your instance name
instance_name = "yourInstanceName"
# Replace yourEndpoint with your instance endpoint
endpoint = "yourEndpoint"
# Get STS credentials from 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 Tablestore client
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)
# List and print table names
resp = client.list_table()
for table_name in resp:
    print(table_name)
Node.js

The following Node.js sample code initializes a client and lists all table names in the instance.

// Adjust the relative path as needed.
var TableStore = require('../index.js');
// Replace yourInstanceName with your instance name
var instancename = 'yourInstanceName';
// Replace yourEndpoint with your instance endpoint
var endpoint = 'yourEndpoint';
// Get STS credentials from 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 Tablestore client
var client = new TableStore.Client({
  accessKeyId: accessKeyId,
  secretAccessKey: accessKeySecret,
  stsToken: stsToken,
  endpoint: endpoint,
  instancename: instancename 
});
// List and print table names
client.listTable({}, function (err, data) {
    if (err) {
        console.log('error:', err);
        return;
    }
    console.log('success:', data);
});
PHP

The following PHP sample code initializes a client and lists all table names in the instance.

<?php
// Adjust the relative path as needed.
require (__DIR__ . '/../../vendor/autoload.php');
use Aliyun\OTS\OTSClient as OTSClient;
// Replace yourInstanceName with your instance name
$instanceName = "yourInstanceName";
// Replace yourEndpoint with your instance endpoint
$endpoint = "yourEndpoint";
// Get STS credentials from environment variables
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
$stsToken = getenv('TABLESTORE_SESSION_TOKEN');
// Initialize Tablestore client
$client = new OTSClient(array(
    'EndPoint' => $endpoint,
    'AccessKeyID' => $accessKeyId,
    'AccessKeySecret' => $accessKeySecret,
    'InstanceName' => $instanceName,
    'StsToken' => $stsToken,
));
// List and print table names
$response = $client->listTable (array ());
print json_encode ($response);

Time series model

When using the time series model, initialize the time series client with STS temporary credentials and send requests. The time series model is supported in Java, Go, and Python.

Java
V4 signature (recommended)

The following Java sample code initializes a client using V4 signature and lists all time series table names in the 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) {
        // Replace yourRegion with your instance region, such as cn-hangzhou
        final String region = "yourRegion";
        // Replace yourInstanceName with your instance name
        final String instanceName = "yourInstanceName";
        // Replace yourEndpoint with your instance endpoint
        final String endpoint = "yourEndpoint";
        // Get STS credentials from 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");
        // Build V4 signature
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
        CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
        // Initialize Tablestore client
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
        /*
        // Customize ClientConfiguration if needed. Examples:
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */
        // List and print time series table names
        ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
        listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        // Shut down Tablestore client
        client.shutdown();
    }
}
V2 signature

The following Java sample code initializes a client using V2 signature and lists all time series table names in the 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) {
        // Replace yourInstanceName with your instance name
        final String instanceName = "yourInstanceName";
        // Replace yourEndpoint with your instance endpoint
        final String endpoint = "yourEndpoint";
        // Get STS credentials from 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");
        // Build V2 signature
        DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret, securityToken);
        CredentialsProvider provider = new DefaultCredentialProvider(credentials);
        // Initialize Tablestore client
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
        /*
        // Customize ClientConfiguration if needed. Examples:
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Connection timeout in milliseconds
        clientConfiguration.setSocketTimeoutInMillisecond(5000); // Socket timeout in milliseconds
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Retry strategy; default used if not set
        TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
         */
        // List and print time series table names
        ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
        listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
        // Shut down Tablestore client
        client.shutdown();
    }
}
Go

The following Go sample code initializes a client and lists all time series table names in the instance.

package main
import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
    // Replace yourInstanceName with your instance name
    instanceName := "yourInstanceName"
    // Replace yourEndpoint with your instance endpoint
    endpoint := "yourEndpoint"
    // Get STS credentials from environment variables
    accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
    accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
    securityToken := os.Getenv("TABLESTORE_SESSION_TOKEN")
    // Initialize Tablestore client
    client := tablestore.NewTimeseriesClientWithConfig(endpoint, instanceName, accessKeyId, accessKeySecret, securityToken, nil, nil)    
    // List and print time series table names
    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 Python sample code initializes a client and lists all time series table names in the instance.

# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# Replace yourInstanceName with your instance name
instance_name = "yourInstanceName"
# Replace yourEndpoint with your instance endpoint
endpoint = "yourEndpoint"
# Get STS credentials from 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 Tablestore client
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name, sts_token=sts_token)
# List and print time series table names
response = client.list_timeseries_table()
for tableMeta in response:
    print(tableMeta.timeseries_table_name)

FAQ

Q: How do I resolve the error You are not authorized to do this action. You should be authorized by RAM.?

When using a RAM user to assume a RAM role and obtain temporary credentials, you must use the RAM user's AccessKey pair (AccessKey ID and AccessKey secret). Do not use the Alibaba Cloud account's AccessKey pair.

Q: How do I resolve the error The Min/Max value of DurationSeconds is 15min/1hr.?

This error occurs when the validity period of the temporary credential exceeds the allowed range. Follow these rules:

  • If you have not customized the role's maximum session duration, the default is 3600 seconds. In this case, the minimum value for durationSeconds is 900 seconds, and the maximum is 3600 seconds.

  • If you have customized the role's maximum session duration, the minimum value for durationSeconds is 900 seconds, and the maximum equals the role's maximum session duration. The role's maximum session duration can be set between 3600 and 43200 seconds.

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

Q: How do I resolve the error The security token you provided is invalid.?

Ensure you enter the complete SecurityToken and verify that your environment variables are configured correctly.

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

Yes. Each request returns one temporary credential. To obtain multiple credentials, send multiple requests. You can use all obtained credentials simultaneously during their validity periods.

Q: What should I do if I get a Request denied by instance ACL policies exception when using the SDK to access Tablestore?

The network type used by your client does not meet the instance's network access requirements. In the Instance Management page of the Tablestore console, go to the Network Management tab and set Allowed Network Types. For more information, see Handle "Request denied by instance ACL policies" exceptions when using the SDK to access Tablestore.