You can use the Security Token Service (STS) to issue temporary access credentials that allow other users to access your Tablestore resources within a specified validity period. Temporary access credentials do not require you to expose your long-term keys and automatically expire after the validity period, which enhances security and flexibility when accessing your Tablestore resources.
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 does not have permanent identity credentials such as a logon password or an AccessKey pair. Instead, the role must be assumed by a trusted entity, such as a RAM user. After the role is successfully assumed, the trusted entity obtains temporary identity credentials in the form of a Security Token Service (STS) token. This token can then be used to access Tablestore as the RAM role.
A RAM role whose trusted entity is an Alibaba Cloud account is used to implement cross-account access and temporary authorization. This topic uses an example of a RAM user assuming a RAM role in the same Alibaba Cloud account to describe how to use temporary access credentials from STS to access Tablestore resources.
Procedure
To use temporary access credentials obtained from STS 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 temporary access credentials from STS. Finally, use the obtained temporary access credentials to initiate requests to access Tablestore resources.
Step 1: Create a RAM role
Log on to the RAM console by using an Alibaba Cloud account or a RAM administrator.
In the left-side navigation pane, choose . The Roles page is displayed.
Click Create Role, configure the trusted entity information, and click OK.
Parameter
Sample value
Principal Type
Cloud account
Principal Name
Current Account
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 ARN of the RAM role. To obtain the ARN, click the role name in the role list to go to the role details page. Then, find and copy the ARN in the Basic Information section.

Step 2: Grant the RAM role Tablestore permissions
Use the default policy
In this example, the AliyunOTSFullAccess policy is attached to the RAM role to grant permissions to access Tablestore.
The AliyunOTSFullAccess policy contains full access permissions on Tablestore. You can also grant permissions in the following ways.
To grant read-only access, attach the
AliyunOTSReadOnlyAccesspolicy to the RAM role.If you need write-only permissions, grant the
AliyunOTSWriteOnlyAccesspermission to the RAM role.
In the left-side navigation pane, choose .
On the Roles page, find the target RAM role.
Click Grant Permission in the Actions column of the RAM role, or click the role name to go to the role details page and click Grant Permission in the Permission Management section.
In the Policy section of the Grant Permission panel, search for and select
AliyunOTSFullAccess.Click Grant Permissions.
Use a custom policy
Create a custom Resource Access Management (RAM) policy.
In the left-side navigation pane, select .
On the Policies page, click Create Policy.
On the Create Policy page, click Script Editor, write a script in the text box, 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 permissions to access a table or call an API operation. You can also grant the RAM role 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*" } ] }In the Create Policy dialog box, enter a policy name, for example,
TestRAMPolicy, and click OK.
Attach the custom policy to the RAM role.
In the left-side navigation pane, choose .
On the Roles page, find the target RAM role.
Click Grant Permission on the right of the RAM role, or click the role name to go to the role details page and click Grant Permission in the Permission Management area.
In the Policy section of the Grant Permission panel, search for and select the custom policy that you created.
Click Grant Permissions.
You can click a role name in the role list to go to the role details page. On the Permissions tab, you can view the attached permission policies.

Step 3: Create a RAM user
Create a RAM user to assume the RAM role.
Log on to the RAM console by using your Alibaba Cloud account or a RAM user who has administrator privileges.
In the left-side navigation pane, choose .
On the Users page, click Create User.
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
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.
NoteYou can click Add User to create multiple RAM users at the same time.
In the Access Mode section, select Using permanent AccessKey to access and click OK.
NoteIf you want to log on to and access the Alibaba Cloud Management Console as a RAM user, select Console Access.
In the Actions column, click Copy to save the information about the RAM user. You can separately copy the AccessKey ID and AccessKey secret.
ImportantAn 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.
In the left-side navigation pane, choose .
On the Users page, find the target RAM user.
Click Add Permissions to the right of the RAM user, or click the user name to go to the user details page and on the Permission Management tab, click Grant Permission.
In the Policy section of the Grant Permission panel, search for and select
AliyunSTSAssumeRoleAccess.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>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
Run the following commands in the command-line interface to append environment variable settings to the
~/.bashrcfile.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'" >> ~/.bashrcRun the following command to allow the changes to take effect:
source ~/.bashrcRun 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
Run the following command in the terminal to check the default Shell type.
echo $SHELLPerform operations based on the default Shell type.
Zsh
Run the following commands to append environment variable settings to the
~/.zshrcfile.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'" >> ~/.zshrcRun the following command to allow the changes to take effect:
source ~/.zshrcRun 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
Run the following commands to append environment variable settings to the
~/.bash_profilefile.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_profileRun the following command to allow the changes to take effect:
source ~/.bash_profileRun 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
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"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
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)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 demonstrates 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.
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 could be exposed, potentially compromising the security of all resources in your account. The following sample code is provided for reference only.
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 for 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 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.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
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.
// The error message.
System.out.println(error.getMessage());
// The URL for troubleshooting.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}For more information about STS SDKs and code examples for other programming languages, see STS SDK overview.
Step 6: Use temporary access credentials to access Tablestore
Preparations
Create an instance and data tables in the Tablestore console.
Obtain the instance name, instance endpoint, and region ID.
ImportantBy default, public network access is disabled for newly created instances. If you need to access resources in an instance over the public network, you must enable public network access for the instance.
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
Run the following commands in the command-line interface to append environment variable settings to the
~/.bashrcfile.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'" >> ~/.bashrcRun the following command to allow the changes to take effect:
source ~/.bashrcRun 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
Run the following command in the terminal to check the default Shell type.
echo $SHELLPerform operations based on the default Shell type.
Zsh
Run the following commands to append environment variable settings to the
~/.zshrcfile.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'" >> ~/.zshrcRun the following command to allow the changes to take effect:
source ~/.zshrcRun 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
Run the following commands to append environment variable settings to the
~/.bash_profilefile.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_profileRun the following command to allow the changes to take effect:
source ~/.bash_profileRun 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
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"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
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)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)
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 Java SDK.
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/tablestoreFor more information, see Install Tablestore Go SDK.
Python
Run the following command to use pip to install Tablestore SDK for Python:
sudo pip install tablestoreFor more information, see Install Tablestore Python SDK.
Node.js
Use npm to run the following command to install Tablestore SDK for Node.js:
npm install tablestoreFor more information, see Install Tablestore Node.js SDK.
.NET
For more information, see Install Tablestore .NET SDK.
PHP
For more information, see Install Tablestore PHP SDK.
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.
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 your instance 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 the Tablestore 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 some 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 the Tablestore 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 the Tablestore 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.
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 your instance resides. Example: cn-hangzhou.
final String region = "yourRegion";
// Specify the name of the instance.
final String instanceName = "yourInstanceName";
// Specify the endpoint of your 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 the TimeSeries 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 some 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 TimeSeries 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 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)