You can use Resource Access Management (RAM) to manage user identities and resource access permissions. Compared with an Alibaba Cloud account, a RAM user provides more secure access to Tablestore resources. This topic describes how to use the AccessKey pair of a RAM user to initiate a request to access Tablestore resources.
Background information
A RAM user is the identity of a real entity. You can create RAM users for an Alibaba Cloud account and grant the RAM users the permissions to access different resources.
Procedure
Before you use the AccessKey pair of a RAM user to access Tablestore, you must create the RAM user and grant the RAM user the permissions to access Tablestore.
Step 1: Create a RAM user
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 2: Grant the RAM user the permissions to access Tablestore
After you create a RAM user, you must grant the RAM user the permissions to access Tablestore.
Use the default policy
In this example, the AliyunOTSFullAccess
policy is attached to the RAM user to grant the RAM user the permissions to access Tablestore.
The AliyunOTSFullAccess
policy contains full access permissions on Tablestore. You can also attach the following policies to the RAM user to grant specific permissions to the RAM user based on your business requirements:
To grant the RAM user read-only access to Tablestore, attach the
AliyunOTSReadOnlyAccess
policy to the RAM user.To grant the RAM user write-only access to Tablestore, attach the
AliyunOTSWriteOnlyAccess
policy to the RAM user.
In the left-side navigation pane, choose
.On the Users page, find the RAM user to which you want to attach the policy.
On the Users page, click Add Permissions in the Actions column of the RAM user.
In the Policy section of the Grant Permission panel, search for and select
AliyunOTSFullAccess
.Click Grant permissions.
Use a custom policy
Create a custom policy.
In the left-side navigation pane, choose
.On the Policies page, click Create Policy.
On the Create Policy page, click the JSON tab, enter the script in the policy document, and then click OK.
NoteThe following sample script grants the RAM user the permissions to access a specific instance. You can specify a custom policy script based on your business requirements. For example, you can grant the RAM user the permissions to access a table or call an API operation, or the permissions to access Tablestore only from a specific IP address or before a specific point in time. For more information about RAM policies, see Create a custom policy.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "ots:*", "Resource": "acs:ots:*:*:instance/your_instance_name*" } ] }
In the Create Policy dialog box, enter a policy name, such as
TestRAMPolicy
, and click OK.
Attach the custom policy to the RAM user.
In the left-side navigation pane, choose
.On the Users page, find the RAM user to which you want to attach the custom policy.
On the Users page, click Add Permissions in the Actions column of the RAM user.
In the Policy section of the Grant Permission panel, search for and select the custom policy you created.
Click Grant permissions.
On the Users page, click the name of a RAM user to go to the user details page. On the Permissions tab of the user details page, you can view the policies that are attached to the RAM user.
Step 3: Use the AccessKey pair of the RAM user to access Tablestore
Preparations
Create an instance and a data table in the Tablestore console.
Obtain the name, endpoint, and region ID of the instance. For more information, see Endpoints and Regions.
ImportantBy default, Internet-based access is diabled for a newly created instance. If you want to access resources in an instance over the Internet, you must enable Internet-based access for the instance. For more information, see Solution.
Install the Tablestore SDK for the required programming language.
Java
If you use Maven to manage Java projects, add the following dependency to the pom.xml file:
<dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>
For more information, see Install Tablestore SDK for Java.
Go
Run the
go mod init <DIRNAME>
command in the project directory to generate the go.mo d file. Then, run the following command to install Tablestore SDK for Go:Note<DIRNAME>
indicates the project directory path. Replace <DIRNAME> with the actual project directory path.go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore
For more information, see Install Tablestore SDK for Go.
Python
Run the following command to use pip to install Tablestore SDK for Python:
sudo pip install tablestore
For more information, see Install Tablestore SDK for Python.
Node.js
Use npm to run the following command to install Tablestore SDK for Node.js:
npm install tablestore
For more information, see Install Tablestore SDK for Node.js.
.NET
For more information, see Install Tablestore SDK for .NET.
PHP
For more information, see Install Tablestore SDK for PHP.
Wide Column model
When you use the Wide Column model, you must use the AccessKey pair of a RAM user to initialize a client for the Wide Column model and initiate a request.
Before you run the code, replace the sample instance information in the code with the actual instance information and save the AccessKey pair of the RAM user to the system environment variables. For more information, see Configure environment variables.
Java
(Recommended) Use a V4 signature
The following sample Java code provides an example on how to use a V4 signature to initialize a client and query the list of data tables in an instance:
import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.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.ListTableResponse;
public class InitClientV4 {
public static void main(String[] args) {
// Specify the region in which the instance that you want to access resides. Example: cn-hangzhou.
final String region = "yourRegion";
// Specify the name of the instance.
final String instanceName = "yourInstanceName";
// Specify the endpoint of the instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from the environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V4 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize a client.
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used.
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// Query the list of data tables in the instance and display the list in the Tablestore console.
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// Shut down the Tablestore client.
client.shutdown();
}
}
Use a V2 signature
The following sample Java code provides an example on how to use a V2 signature to initialize a client and query the list of data tables in an instance:
import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.ListTableResponse;
public class InitClientV2 {
public static void main(String[] args) {
// Specify the name of the instance.
final String instanceName = "yourInstanceName";
// Specify the endpoint of the instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from the environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V2 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
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 AccessKey ID and AccessKey secret from the environment variables.
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// Initialize a client.
client := tablestore.NewClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// 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 AccessKey ID and AccessKey secret from the environment variables.
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
# Initialize a client.
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
# 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 AccessKey ID and AccessKey secret from the environment variables.
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;
// Initialize a client.
var client = new TableStore.Client({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
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);
});
.NET
The following sample .NET code provides an example on how to initialize a client and query the list of data tables in an instance:
using Aliyun.OTS.Request;
using Aliyun.OTS.Response;
using System;
namespace Aliyun.OTS.Samples
{
public class Sample
{
public static void Main()
{
// Specify the endpoint of the instance.
string endpoint = "yourEndpoint";
// Specify the name of the instance.
string instanceName = "yourInstanceName";
// Obtain the AccessKey ID and AccessKey secret from the environment variables.
string accessKeyId = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID");
string accessKeySecret = Environment.GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET");
OTSClientConfig config = new OTSClientConfig(endpoint, accessKeyId, accessKeySecret, instanceName)
{
OTSDebugLogHandler = null,
OTSErrorLogHandler = null
};
try
{
// Initialize a client.
OTSClient otsClient = new OTSClient(config);
// Query the list of data tables in the instance and display the list in the Tablestore console.
ListTableResponse response = otsClient.ListTable(new ListTableRequest());
foreach (var tableName in response.TableNames)
{
Console.WriteLine(tableName);
}
}
catch (Exception ex)
{
Console.WriteLine("List table failed, exception:{0}", ex.Message);
}
}
}
}
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 AccessKey ID and AccessKey secret from the system environment variables.
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
// Initialize a client.
$otsClient = new OTSClient(array(
'EndPoint' => $endpoint,
'AccessKeyID' => $accessKeyId,
'AccessKeySecret' => $accessKeySecret,
'InstanceName' => $instanceName,
));
// 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 AccessKey pair of a RAM user to initialize a client for the TimeSeries model and initiate a request. Only Tablestore SDK for Java, Tablestore SDK for Go, and Tablestore SDK for Python support the TimeSeries model.
Before you run the code, replace the sample instance information in the code with the actual instance information and save the AccessKey pair of the RAM user to the system environment variables. For more information, see Configure environment variables.
Java
(Recommended) Use a V4 signature
The following sample Java code provides an example on how to use a V4 signature to initialize a client and query the list of time series tables in an instance:
import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.core.auth.V4Credentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;
public class InitTimeseriesClientV4 {
public static void main(String[] args) {
// Specify the region in which the instance that you want to access resides. Example: cn-hangzhou.
final String region = "yourRegion";
// Specify the name of the instance.
final String instanceName = "yourInstanceName";
// Specify the endpoint of the instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from the environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V4 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// Initialize a client.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// You can use ClientConfiguration to modify the default configurations. The following example includes specific custom configurations.
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // Specify the timeout period for establishing a connection. Unit: milliseconds.
clientConfiguration.setSocketTimeoutInMillisecond(5000); // Specify the socket timeout period. Unit: milliseconds.
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // Specify a retry policy. If you do not specify a retry policy, the default retry policy is used.
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// Query the list of time series tables in the instance and display the list in the Tablestore console.
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// Shut down the TimeSeriesClient.
client.shutdown();
}
}
Use a V2 signature
The following sample Java code provides an example on how to use a V2 signature to initialize a client and query the list of time series tables in an instance:
import com.alicloud.openservices.tablestore.ClientConfiguration;
import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.core.ResourceManager;
import com.alicloud.openservices.tablestore.core.auth.CredentialsProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentialProvider;
import com.alicloud.openservices.tablestore.core.auth.DefaultCredentials;
import com.alicloud.openservices.tablestore.model.AlwaysRetryStrategy;
import com.alicloud.openservices.tablestore.model.timeseries.ListTimeseriesTableResponse;
public class InitTimeseriesClientV2 {
public static void main(String[] args) {
// Specify the name of the instance.
final String instanceName = "yourInstanceName";
// Specify the endpoint of the instance.
final String endpoint = "yourEndpoint";
// Obtain the AccessKey ID and AccessKey secret from the environment variables.
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// Construct a V2 signature.
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
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 AccessKey ID and AccessKey secret from the environment variables.
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// Initialize a client.
client := tablestore.NewTimeseriesClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// 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 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 AccessKey ID and AccessKey secret from the environment variables.
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// Initialize a client.
client := tablestore.NewTimeseriesClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// 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())
}
}
}
Configure environment variables
If you save access credentials to the code, information leaks may occur. We recommend that you save access credentials to system environment variables.
Windows
Run the command prompt as an administrator and execute the following commands:
# Specify the AccessKey ID of the RAM user.
setx TABLESTORE_ACCESS_KEY_ID your_access_key_id /m
# Specify the AccessKey secret of the RAM user.
setx TABLESTORE_ACCESS_KEY_SECRET your_access_key_secret /m
macOS/Linux/Unix
# Specify the AccessKey ID of the RAM user.
export TABLESTORE_ACCESS_KEY_ID=your_access_key_id
# Specify the AccessKey secret of the RAM user.
export TABLESTORE_ACCESS_KEY_SECRET=your_access_key_secret