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
-
Log on to the Resource Access Management (RAM) console using your Alibaba Cloud account (main account) or as a RAM administrator.
-
In the navigation pane on the left, choose to go to the Roles page.
-
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
-
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.
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
AliyunOTSReadOnlyAccesspolicy. -
For write-only permission, grant the RAM role the
AliyunOTSWriteOnlyAccesspolicy.
-
In the navigation pane on the left, choose .
-
On the Roles page, find the target RAM role.
-
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.
-
In the Grant Permission panel, in the Access Policy section, search for
AliyunOTSFullAccessand select it. -
Click Confirm New Authorization.
Use a custom policy
-
Create a custom policy.
-
In the navigation pane on the left, choose .
-
On the Policies page, click Create Policy.
-
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*" } ] } -
In the Create Policy dialog box, enter a policy name such as
TestRAMPolicy, and click OK.
-
-
Grant the custom policy to the RAM role.
-
In the navigation pane on the left, choose .
-
On the Roles page, find the target RAM role.
-
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.
-
In the Grant Permission panel, in the Access Policy section, search for and select the custom access policy you created.
-
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.
Log on to the RAM console by using your Alibaba Cloud account or a RAM user that has administrative permissions.
In the navigation pane on the left, choose Identities > Users.
On the Users page, click Create User.
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
icon and enter a tag key and a tag value. Adding a tag helps you find and manage the RAM user.
NoteYou can click Add User to create multiple RAM users in a batch.
In the Access Mode section, select Programmatic Access, and then click OK.
NoteTo allow the RAM user to log on to the Alibaba Cloud Management Console, select Console Access.
In the Actions column, click Copy to save the RAM user information. You can also copy the AccessKey ID and AccessKey secret individually.
ImportantThe 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.
-
In the navigation pane on the left, choose .
-
On the Users page, find the target RAM user.
-
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.
-
In the Grant Permission panel's access policy section, search for
AliyunSTSAssumeRoleAccessand select it. -
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
-
Add the following dependency to your 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 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
-
Create an instance and data tables in the Tablestore console.
-
Obtain the instance name, instance endpoint, and region ID.
ImportantNew instances do not enable public network access by default. If you need public network access, 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 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/tablestoreFor 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 tablestoreFor more information, see Install Tablestore SDK for Python.
Node.js
Run the following command to install the Tablestore SDK for Node.js:
npm install tablestoreFor 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)