访问控制RAM可以帮助您管理用户身份和资源访问权限,使用RAM用户访问表格存储资源比直接使用阿里云账号更加安全。本文介绍如何使用RAM用户的访问密钥发起请求访问表格存储资源。
背景信息
RAM用户即RAM账号,是访问控制RAM(Resource Access Management)的一种实体身份类型。您可以为阿里云账号(主账号)创建RAM用户并为其授权,实现不同RAM用户拥有不同资源访问权限的目的。
操作步骤
使用RAM用户访问密钥访问表格存储,您需要创建一个RAM用户并授予其访问表格存储的权限,再用RAM用户的访问密钥发起请求,访问表格存储资源。
步骤一:创建RAM用户
使用阿里云账号(主账号)或RAM管理员登录RAM控制台。
在左侧导航栏,选择。
在用户页面,单击创建用户。
在创建用户页面的用户账号信息区域,设置用户基本信息。
登录名称:可包含英文字母、数字、半角句号(.)、短划线(-)和下划线(_),最多64个字符。
显示名称:最多包含128个字符或汉字。
标签:单击
,输入标签键和标签值。为RAM用户绑定标签,便于后续基于标签管理用户。
说明通过单击添加用户,您可以批量创建多个RAM用户。
在访问方式区域,选中使用永久AccessKey访问,单击确定。
说明如果需要使用RAM用户登录和访问阿里云控制台,请选中控制台访问。
根据界面提示,完成安全验证。
单击操作列的复制,保存RAM用户信息。您也可以单独复制AccessKey ID和AccessKey Secret。
重要RAM用户的AccessKey Secret只在创建时显示,页面关闭后将无法查看,请及时保存并妥善保管。
步骤二:为RAM用户授予访问表格存储权限
创建RAM用户后,您需要为RAM用户授予表格存储的访问权限。
使用默认策略
以 AliyunOTSFullAccess 为例授予RAM用户访问表格存储的权限。
AliyunOTSFullAccess 拥有表格存储的完全访问权限,您也可以选择以下方式进行授权。
如果需要只读权限,请授予RAM用户
AliyunOTSReadOnlyAccess权限。如果需要只写权限,请授予RAM用户
AliyunOTSWriteOnlyAccess权限。
在左侧导航栏,选择。
在用户页面,找到目标RAM用户。
单击RAM用户右侧的添加权限。
在新增授权面板的权限策略区域,搜索
AliyunOTSFullAccess并选中。单击确认新增授权。
使用自定义策略
创建自定义权限策略。
在左侧导航栏,选择。
在权限策略页面,单击创建权限策略。
在创建权限策略页面,单击脚本编辑,并在输入框中编写脚本,单击确定。
说明以下示例脚本授予RAM用户访问单个实例的权限,您可以根据需要自定义策略脚本,例如表和API级别的权限控制或基于场景(IP、访问时间限制等)的权限控制。关于RAM Policy的更多信息,请参见自定义RAM Policy。
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "ots:*", "Resource": "acs:ots:*:*:instance/your_instance_name*" } ] }在创建权限策略对话框,填写策略名称,例如
TestRAMPolicy,单击确定。
为RAM用户授予自定义权限策略。
在左侧导航栏,选择。
在用户页面,找到目标RAM用户。
单击RAM用户右侧的添加权限。
在新增授权面板的权限策略区域,搜索并选中已创建的自定义权限策略。
单击确认新增授权。
您可以在用户列表单击用户名称进入用户详情页,在权限管理页签下查看被授权的权限策略。

步骤三:使用RAM用户访问密钥访问表格存储
准备工作
在表格存储控制台创建实例和数据表。
获取实例名称、实例访问地址、地域ID。
重要新创建的实例默认未启用公网访问功能。如果您需要通过公网访问实例中的资源,则必须开启实例的公网访问功能。
根据不同的编程语言,安装对应的Tablestore SDK。
Java
如果您使用的是Maven项目,请在项目的pom.xml文件中添加如下依赖:
<dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>更多信息,请参见安装Tablestore Java SDK。
Go
在项目目录中执行
go mod init <DIRNAME>命令生成go.mod文件后,执行如下命令安装表格存储Go SDK。说明<DIRNAME>为项目目录路径,请以实际路径为准。go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore更多信息,请参见安装Tablestore Go SDK。
Python
执行如下命令直接通过pip进行SDK安装。
sudo pip install tablestore更多信息,请参见安装Tablestore Python SDK。
Node.js
通过npm执行如下命令安装表格存储Node.js SDK。
npm install tablestore说明如果使用npm遇到网络问题,您可以使用淘宝提供的npm镜像。具体网址请参见cnpm。
更多信息,请参见安装Tablestore Node.js SDK。
.NET
具体操作,请参见安装Tablestore .NET SDK。
PHP
具体操作,请参见安装Tablestore PHP SDK。
宽表模型
使用宽表模型时,您需要使用RAM用户的访问密钥初始化宽表模型客户端,并发起相应请求。
运行代码前请替换代码内的实例信息,并将RAM用户的AccessKey配置到系统环境变量。
Java
V4签名(推荐)
以下Java示例代码使用V4签名初始化Client,并获取实例中的所有数据表名称。
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) {
// yourRegion 填写您的实例所在地域,如 cn-hangzhou
final String region = "yourRegion";
// yourInstanceName 填写您的实例名称
final String instanceName = "yourInstanceName";
// yourEndpoint 填写您的实例访问地址
final String endpoint = "yourEndpoint";
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// 构造 V4 签名
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// 初始化表格存储客户端
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// 您可以通过指定 ClientConfiguration 修改默认配置项,以下示例为部分自定义配置项。
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // 设置建立连接的超时时间,单位为毫秒。
clientConfiguration.setSocketTimeoutInMillisecond(5000); // 设置 socket 超时时间,单位为毫秒。
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // 设置重试策略,如果不设置,则采用默认的重试策略。
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// 列出实例中的数据表列表并打印到控制台
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// 关闭 Tablestore Client
client.shutdown();
}
}V2签名
以下Java示例代码使用V2签名初始化Client,并获取实例中的所有数据表名称。
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) {
// yourInstanceName 填写您的实例名称
final String instanceName = "yourInstanceName";
// yourEndpoint 填写您的实例访问地址
final String endpoint = "yourEndpoint";
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// 构造 V2 签名
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// 初始化表格存储客户端
SyncClient client = new SyncClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// 您可以通过指定 ClientConfiguration 修改默认配置项,以下示例为部分自定义配置项。
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // 设置建立连接的超时时间,单位为毫秒。
clientConfiguration.setSocketTimeoutInMillisecond(5000); // 设置 socket 超时时间,单位为毫秒。
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // 设置重试策略,如果不设置,则采用默认的重试策略。
SyncClient client = new SyncClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// 列出实例中的数据表列表并打印到控制台
ListTableResponse listTableResponse = client.listTable();
listTableResponse.getTableNames().forEach(System.out::println);
// 关闭 Tablestore Client
client.shutdown();
}
}Go
以下Go示例代码用于初始化Client,并获取实例中的所有数据表名称。
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// yourInstanceName 填写您的实例名称
instanceName := "yourInstanceName"
// yourEndpoint 填写您的实例访问地址
endpoint := "yourEndpoint"
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// 初始化表格存储客户端
client := tablestore.NewClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// 列出实例中的数据表列表并打印到控制台
tables, err := client.ListTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, table := range (tables.TableNames) {
fmt.Println(table)
}
}
}Python
以下Python示例代码用于初始化Client,并获取实例中的所有数据表名称。
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# yourInstanceName 填写您的实例名称
instance_name = "yourInstanceName"
# yourEndpoint 填写您的实例访问地址
endpoint = "yourEndpoint"
# 获取环境变量里的 AccessKey ID 和 AccessKey Secret
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
# 初始化表格存储客户端
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
# 列出实例中的数据表列表并打印到控制台
resp = client.list_table()
for table_name in resp:
print(table_name)Node.js
以下Node.js示例代码用于初始化Client,并获取实例中的所有数据表名称。
// 此处为相对路径,请根据实际情况进行调整。
var TableStore = require('../index.js');
// yourInstanceName 填写您的实例名称
var instancename = 'yourInstanceName';
// yourEndpoint 填写您的实例访问地址
var endpoint = 'yourEndpoint';
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
var accessKeyId = process.env.TABLESTORE_ACCESS_KEY_ID;
var secretAccessKey = process.env.TABLESTORE_ACCESS_KEY_SECRET;
// 初始化表格存储客户端
var client = new TableStore.Client({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
endpoint: endpoint,
instancename: instancename
});
// 列出实例中的数据表列表并打印到控制台
client.listTable({}, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('success:', data);
}); .NET
以下 .NET 示例代码用于初始化Client,并获取实例中的所有数据表名称。
using Aliyun.OTS.Request;
using Aliyun.OTS.Response;
using System;
namespace Aliyun.OTS.Samples
{
public class Sample
{
public static void Main()
{
// yourEndpoint 填写您的实例访问地址
string endpoint = "yourEndpoint";
// yourInstanceName 填写您的实例名称
string instanceName = "yourInstanceName";
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
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
{
// 初始化表格存储客户端
OTSClient otsClient = new OTSClient(config);
// 列出实例中的数据表列表并打印
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
以下PHP示例代码用于初始化Client,并获取实例中的所有数据表名称。
<?php
// 此处为相对路径,请根据实际情况进行调整。
require (__DIR__ . '/../../vendor/autoload.php');
use Aliyun\OTS\OTSClient as OTSClient;
// yourInstanceName 填写您的实例名称
$instanceName = "yourInstanceName";
// yourEndpoint 填写您的实例访问地址
$endpoint = "yourEndpoint";
// 获取系统变量里的 AccessKey ID 和 AccessKey Secret
$accessKeyId = getenv('TABLESTORE_ACCESS_KEY_ID');
$accessKeySecret = getenv('TABLESTORE_ACCESS_KEY_SECRET');
// 初始化表格存储客户端
$otsClient = new OTSClient(array(
'EndPoint' => $endpoint,
'AccessKeyID' => $accessKeyId,
'AccessKeySecret' => $accessKeySecret,
'InstanceName' => $instanceName,
));
// 列出实例中的数据表列表并打印到控制台
$response = $otsClient->listTable (array ());
print json_encode ($response);时序模型
使用时序模型时,您需要使用RAM用户的访问密钥初始化时序模型客户端,并发起相应请求。目前Java、Go和Python语言支持操作时序模型。
运行代码前请替换代码内的实例信息,并将RAM用户的AccessKey配置到系统环境变量。
Java
V4签名(推荐)
以下Java示例代码使用V4签名初始化Client,并获取实例中的所有时序表名称。
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) {
// yourRegion 填写您的实例所在地域,如 cn-hangzhou
final String region = "yourRegion";
// yourInstanceName 填写您的实例名称
final String instanceName = "yourInstanceName";
// yourEndpoint 填写您的实例访问地址
final String endpoint = "yourEndpoint";
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// 构造 V4 签名
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
V4Credentials credentialsV4 = V4Credentials.createByServiceCredentials(credentials, region);
CredentialsProvider provider = new DefaultCredentialProvider(credentialsV4);
// 初始化表格存储客户端
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// 您可以通过指定 ClientConfiguration 修改默认配置项,以下示例为部分自定义配置项。
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // 设置建立连接的超时时间,单位为毫秒。
clientConfiguration.setSocketTimeoutInMillisecond(5000); // 设置 socket 超时时间,单位为毫秒。
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // 设置重试策略,如果不设置,则采用默认的重试策略。
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// 列出实例中的时序表列表并打印到控制台
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// 关闭 Tablestore Client
client.shutdown();
}
}V2签名
以下Java示例代码使用V2签名初始化Client,并获取实例中的所有时序表名称。
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) {
// yourInstanceName 填写您的实例名称
final String instanceName = "yourInstanceName";
// yourEndpoint 填写您的实例访问地址
final String endpoint = "yourEndpoint";
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
final String accessKeyId = System.getenv("TABLESTORE_ACCESS_KEY_ID");
final String accessKeySecret = System.getenv("TABLESTORE_ACCESS_KEY_SECRET");
// 构造 V2 签名
DefaultCredentials credentials = new DefaultCredentials(accessKeyId, accessKeySecret);
CredentialsProvider provider = new DefaultCredentialProvider(credentials);
// 初始化表格存储客户端
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, null, new ResourceManager(null, null));
/*
// 您可以通过指定 ClientConfiguration 修改默认配置项,以下示例为部分自定义配置项。
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeoutInMillisecond(5000); // 设置建立连接的超时时间,单位为毫秒。
clientConfiguration.setSocketTimeoutInMillisecond(5000); // 设置 socket 超时时间,单位为毫秒。
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy()); // 设置重试策略,如果不设置,则采用默认的重试策略。
TimeseriesClient client = new TimeseriesClient(endpoint, provider, instanceName, clientConfiguration, new ResourceManager(null, null));
*/
// 列出实例中的时序表列表并打印到控制台
ListTimeseriesTableResponse listTimeseriesTableResponse = client.listTimeseriesTable();
listTimeseriesTableResponse.getTimeseriesTableNames().forEach(System.out::println);
// 关闭 Tablestore Client
client.shutdown();
}
}Go
以下Go示例代码用于初始化Client,并获取实例中的所有时序表名称。
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)
func main() {
// yourInstanceName 填写您的实例名称
instanceName := "yourInstanceName"
// yourEndpoint 填写您的实例访问地址
endpoint := "yourEndpoint"
// 获取环境变量里的 AccessKey ID 和 AccessKey Secret
accessKeyId := os.Getenv("TABLESTORE_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("TABLESTORE_ACCESS_KEY_SECRET")
// 初始化表格存储客户端
client := tablestore.NewTimeseriesClient(endpoint, instanceName, accessKeyId, accessKeySecret)
// 列出实例下的时序表列表并打印到控制台
timeseriesTables, err := client.ListTimeseriesTable()
if err != nil {
fmt.Println("Failed to list table")
} else {
for _, timeseriesTablesMeta := range (timeseriesTables.GetTimeseriesTableMeta()) {
fmt.Println(timeseriesTablesMeta.GetTimeseriesTableName())
}
}
}Python
以下Python示例代码用于初始化Client,并获取实例中的所有时序表名称。
# -*- coding: utf-8 -*-
import os
from tablestore import OTSClient
# yourInstanceName 填写您的实例名称
instance_name = "yourInstanceName"
# yourEndpoint 填写您的实例访问地址
endpoint = "yourEndpoint"
# 获取环境变量里的 AccessKey ID 和 AccessKey Secret
access_key_id = os.getenv("TABLESTORE_ACCESS_KEY_ID")
access_key_secret = os.getenv("TABLESTORE_ACCESS_KEY_SECRET")
# 初始化表格存储客户端
client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
# 列出实例中的时序表列表并打印到控制台
response = client.list_timeseries_table()
for tableMeta in response:
print(tableMeta.timeseries_table_name)配置环境变量
直接在代码中保存访问凭证容易导致信息泄露,建议您按以下操作将访问凭证保存在系统环境变量中。
Windows
以管理员身份运行命令提示符,执行以下命令。
# 配置 RAM 用户的 AccessKey ID
setx TABLESTORE_ACCESS_KEY_ID your_access_key_id /m
# 配置 RAM 用户的 AccessKey Secret
setx TABLESTORE_ACCESS_KEY_SECRET your_access_key_secret /mmacOS/Linux/Unix
# 配置 RAM 用户的 AccessKey ID
export TABLESTORE_ACCESS_KEY_ID=your_access_key_id
# 配置 RAM 用户的 AccessKey Secret
export TABLESTORE_ACCESS_KEY_SECRET=your_access_key_secret