Tüm Ürünler
Search
Belge Merkezi

Tablestore:Use STS temporary credentials to access Tablestore

Son Güncelleme:Oct 02, 2026

Security Token Service (STS) kullanarak başka bir kullanıcıya geçici bir erişim kimlik bilgisi verebilirsiniz. Kullanıcı, bu kimlik bilgisinin geçerlilik süresi içinde Tablestore kaynaklarına erişmek için bu kimlik bilgisini kullanabilir. Geçici kimlik bilgileri uzun vadeli anahtarlarınızı ifşa etmez. Süre dolduğunda otomatik olarak geçersiz hale gelirler; böylece Tablestore kaynaklarınıza erişim daha esnek ve güvenli olur.

Arka plan bilgileri

RAM rolü, belirli kaynaklara erişmek için izin verilebilen sanal bir kullanıcıdır. RAM kullanıcısından farklı olarak RAM rolünün kalıcı kimlik bilgileri (oturum açma parolası veya AccessKey çifti gibi) yoktur. Güvenilir bir varlığın (örneğin bir RAM kullanıcısının) rolü üstlenmesi gerekir. Başarılı üstlenmenin ardından güvenilir varlık, RAM rolü için geçici kimlik bilgileri—yani bir Security Token Service belirteci (STS Token)—alır ve bu belirteci kullanarak RAM rolü adına Tablestore hizmetine erişebilir.

Alibaba Cloud hesapları için RAM rolleri öncelikle hesaplar arası erişim ve geçici yetkilendirme senaryolarını ele alır. Bu konuda, aynı hesap içindeki bir RAM kullanıcısının bir RAM rolünü nasıl üstlendiğine dair bir örnek üzerinden STS geçici kimlik bilgilerini kullanarak Tablestore kaynaklarına erişim gösterilmektedir.

Yordam

STS geçici kimlik bilgilerini kullanarak Tablestore hizmetine erişmek için öncelikle üstlenilecek bir RAM rolü oluşturun ve bu role Tablestore erişim izni verin. Ardından, RAM rolünü üstlenecek bir RAM kullanıcısı oluşturun ve STS geçici kimlik bilgilerini alın. Son olarak, bu kimlik bilgilerini kullanarak Tablestore kaynaklarına istek gönderin.

1. Adım: RAM rolü oluşturma

  1. Alibaba Cloud hesabınızla (ana hesap) veya RAM yöneticisi olarak Resource Access Management (RAM) konsoluna giriş yapın.

  2. Sol gezinme bölmesinde Identities > Roles seçeneğini belirterek Roles sayfasına gidin.

  3. Create Role düğmesini tıklayın, güvenilir varlığı yapılandırın ve OK düğmesine tıklayın.


    Parameter


    Example value


    Trusted entity type


    Alibaba Cloud account


    Trusted entity name


    Current Alibaba Cloud account

  4. Create Role iletişim kutusunda Role Name alanını RamTablestore olarak ayarlayın ve OK düğmesine tıklayın.

STS aracılığıyla geçici kimlik bilgileri alırken RAM rolünün ARN değerini belirtmeniz gerekir. Rolün ayrıntılar sayfasındaki Basic Information bölümünden ARN değerini bulup kopyalayabilirsiniz.

Bu rolün ARN biçimi acs:ram::<Alibaba Cloud account ID>:role/ramtablestore şeklindedir. ARN değerini almak için yanındaki Copy düğmesine tıklayın.

2. Adım:Tablestoreerişim izinlerini verme

Varsayılan bir ilke kullanma

AliyunOTSFullAccess ilkesini kullanarak RAM rolüne Tablestore erişim izni verin.

Not

AliyunOTSFullAccess ilkesi Tablestore üzerinde tam erişim sağlar. Aşağıdaki seçeneklerden birini de tercih edebilirsiniz:

  • Salt okunur erişim için RAM rolüne AliyunOTSReadOnlyAccess ilkesini atayın.

  • Salt yazma erişimi için RAM rolüne AliyunOTSWriteOnlyAccess ilkesini atayın.

  1. Sol gezinme bölmesinde Identities > Roles seçeneğini belirleyin.

  2. Roles sayfasında hedef RAM rolünü bulun.

  3. RAM rolünün yanındaki Attach Policy düğmesine tıklayın veya rol adına tıklayarak ayrıntılar sayfasına gidin ve Permissions bölümündeki Grant Permission düğmesine tıklayın.

  4. Grant Permission panelinde Access Policy bölümünde AliyunOTSFullAccess ilkesini aratın ve seçin.

  5. Confirm New Authorization düğmesine tıklayın.

Özel bir ilke kullanma

  1. Özel bir ilke oluşturun.

    1. Sol gezinme bölmesinde Permissions > Policies seçeneğini belirleyin.

    2. Policies sayfasında Create Policy düğmesine tıklayın.

    3. Create Policy sayfasında Script Editor sekmesine tıklayın, giriş kutusuna betiği girin ve OK düğmesine tıklayın.

      Aşağıdaki örnek betik tek bir örneğe erişim izni verir. İhtiyaca göre ilke betiğini özelleştirin; örneğin, tablo veya API düzeyinde izinleri kontrol edin ya da IP adresi veya erişim zamanı gibi koşullara dayalı kısıtlamalar ekleyin. RAM ilkeleri hakkında daha fazla bilgi için bkz. Özel RAM ilkeleri .
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "ots:*",
            "Resource": "acs:ots:*:*:instance/your_instance_name*"
          }
        ]
      }
    4. Create Policy iletişim kutusunda TestRAMPolicy gibi bir ilke adı girin ve OK düğmesine tıklayın.

  1. Özel ilkeyi RAM rolüne atayın.

    1. Sol gezinme bölmesinde Identities > Roles seçeneğini belirleyin.

    2. Roles sayfasında hedef RAM rolünü bulun.

    3. RAM rolünün yanındaki Attach Policy düğmesine tıklayın veya rol adına tıklayarak ayrıntılar sayfasına gidin ve Permissions bölümündeki Grant Permission düğmesine tıklayın.

    4. Grant Permission panelinde Access Policy bölümünde oluşturduğunuz özel erişim ilkesini aratın ve seçin.

    5. Confirm düğmesine tıklayın.

Rolün ayrıntılar sayfasındaki Permissions sekmesinden atanmış ilkeleri görüntüleyebilirsiniz.

3. Adım: RAM kullanıcısı oluşturma

RAM rolünü üstlenecek bir RAM kullanıcısı oluşturun.

  1. Alibaba Cloud hesabınızı veya yönetici izinlerine sahip bir RAM kullanıcısını kullanarak RAM konsoluna giriş yapın.

  2. Sol gezinme bölmesinde Identities > Users seçeneğini belirleyin.

  3. Users sayfasında Create User düğmesine tıklayın.

  4. Create User sayfasında User Account Information bölümünde kullanıcının temel bilgilerini yapılandırın:

    • Logon Name: Oturum açma adı harf, rakam, nokta (.), kısa çizgi (-) ve alt çizgi (_) içerebilir. Uzunluğu en fazla 64 karakter olabilir.

    • Display Name: Görünen adın uzunluğu en fazla 128 karakter olabilir.

    • Tag: edit simgesine tıklayarak edit bir etiket anahtarı ve değeri girin. Etiket eklemek, RAM kullanıcısını bulmanıza ve yönetmenize yardımcı olur.

    Not

    Birden çok RAM kullanıcısını toplu olarak oluşturmak için Add User düğmesine tıklayabilirsiniz.

  5. Access Mode bölümünde Programmatic Access seçeneğini işaretleyin ve ardından OK düğmesine tıklayın.

    Not

    RAM kullanıcısının Alibaba Cloud Management Console'a oturum açmasına izin vermek için Console Access seçeneğini işaretleyin.

  6. Actions sütununda RAM kullanıcı bilgilerini kaydetmek için Copy düğmesine tıklayın. AccessKey ID ve AccessKey secret değerlerini tek tek de kopyalayabilirsiniz.

    Önemli

    AccessKey secret yalnızca oluşturma sırasında bir kez gösterilir ve daha sonra alınamaz. Hemen güvenli bir konumda saklayın.

4. Adım: RAM kullanıcısına AssumeRole çağırma izni verme

Bir RAM rolünü üstlenmek için RAM kullanıcısının AssumeRole işlemini çağırma iznine sahip olması gerekir.

  1. Sol gezinme bölmesinde Identities > Users seçeneğini belirleyin.

  2. Users sayfasında hedef RAM kullanıcısını bulun.

  3. RAM kullanıcısının yanındaki Add Permissions düğmesine tıklayın veya kullanıcı adına tıklayarak ayrıntılar sayfasına gidin ve Permission Management sekmesindeki Grant Permission düğmesine tıklayın.

  4. Grant Permission panelinin access policy bölümünde AliyunSTSAssumeRoleAccess ilkesini aratın ve seçin.

  5. Confirm düğmesine tıklayın.

5. Adım: RAM kullanıcısıyla RAM rolünü üstlenme ve geçici kimlik bilgilerini alma

Kaynaklara erişmeden önce RAM kullanıcısını kullanarak RAM rolünü üstlenin ve geçici kimlik bilgilerini alın. Bu kimlik bilgileri yalnızca geçerlilik süreleri boyunca kullanılabilir. Bu örnekte Java kullanılmaktadır.

Geçici kimlik bilgilerini almak için doğrudan OpenAPI Explorer'da AssumeRole işlemini çağırabilirsiniz .

Hazırlıklar

  1. Aşağıdaki bağımlılığı Maven projenize ekleyin.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>sts20150401</artifactId>
        <version>1.1.6</version>
    </dependency>
  2. Ortam değişkenlerini yapılandırın. Yapılandırma tamamlandıktan sonra IDE, komut satırı arabirimi, diğer masaüstü uygulamaları ve arka plan hizmetleri dahil olmak üzere derleme ve çalışma zamanı ortamınızı yeniden başlatın veya yenileyerek en son sistem ortam değişkenlerinin başarıyla yüklendiğinden emin olun.

    Linux

    1. Komut satırı arabiriminde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bashrc dosyasına ekleyin.

      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bashrc
    2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

      source ~/.bashrc
    3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
      echo $TABLESTORE_STS_ROLE_ARN

    macOS

    1. Terminalde varsayılan Shell türünü kontrol etmek için aşağıdaki komutu çalıştırın.

      echo $SHELL
    2. Varsayılan Shell türüne göre işlemleri gerçekleştirin.

      Zsh

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.zshrc dosyasına ekleyin.

        echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.zshrc
      2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

        source ~/.zshrc
      3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

        echo $ALIBABA_CLOUD_ACCESS_KEY_ID
        echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
        echo $TABLESTORE_STS_ROLE_ARN

      Bash

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bash_profile dosyasına ekleyin.

        echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        echo "export TABLESTORE_STS_ROLE_ARN='YOUR_RAM_ROLE_ARN'" >> ~/.bash_profile
      2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

        source ~/.bash_profile
      3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

        echo $ALIBABA_CLOUD_ACCESS_KEY_ID
        echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
        echo $TABLESTORE_STS_ROLE_ARN

    Windows

    CMD

    1. CMD'de ortam değişkenlerini ayarlamak için aşağıdaki komutları çalıştırın.

      setx ALIBABA_CLOUD_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx ALIBABA_CLOUD_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      setx TABLESTORE_STS_ROLE_ARN "YOUR_RAM_ROLE_ARN"
    2. CMD'yi yeniden başlattıktan sonra ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
      echo %TABLESTORE_STS_ROLE_ARN%

    PowerShell

    1. PowerShell'de aşağıdaki komutu çalıştırın:

      [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_STS_ROLE_ARN", "YOUR_RAM_ROLE_ARN", [EnvironmentVariableTarget]::User)
    2. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      [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)

Örnek kod

Aşağıdaki örnek kod, bir RAM kullanıcısı kullanarak bir RAM rolünü üstlenir, STS geçici kimlik bilgilerini alır ve bunları konsola yazdırır. Kimlik bilgilerinin geçerlilik süresi bir saattir.

STS uç noktalarının listesi için bkz. Uç noktalar .
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);
        }
    }
}

Diğer dillerdeki STS SDK'ları ve kod örnekleri için bkz. STS SDK'larına genel bakış.

6. Adım: Geçici erişim kimlik bilgilerini kullanarakTablestorehizmetine erişme

Hazırlıklar

  1. Tablestore konsolunda bir örnek ve veri tabloları oluşturun.

  2. Örnek adını, örnek uç noktasını ve bölge kimliğini alın.

    Önemli

    Yeni örneklerde varsayılan olarak genel ağ erişimi etkin değildir. Genel ağ erişimine ihtiyacınız varsa örnek için genel ağ erişimini etkinleştirin.

  3. Ortam değişkenlerini yapılandırın. Yapılandırma tamamlandıktan sonra IDE, komut satırı arabirimi, diğer masaüstü uygulamaları ve arka plan hizmetleri dahil olmak üzere derleme ve çalışma zamanı ortamınızı yeniden başlatın veya yenileyerek en son sistem ortam değişkenlerinin başarıyla yüklendiğinden emin olun.

    Linux

    1. Komut satırı arabiriminde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bashrc dosyasına ekleyin.

      echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bashrc
      echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bashrc
    2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

      source ~/.bashrc
    3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      echo $TABLESTORE_ACCESS_KEY_ID
      echo $TABLESTORE_ACCESS_KEY_SECRET
      echo $TABLESTORE_SESSION_TOKEN

    macOS

    1. Terminalde varsayılan Shell türünü kontrol etmek için aşağıdaki komutu çalıştırın.

      echo $SHELL
    2. Varsayılan Shell türüne göre işlemleri gerçekleştirin.

      Zsh

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.zshrc dosyasına ekleyin.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.zshrc
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.zshrc
      2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

        source ~/.zshrc
      3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

        echo $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN

      Bash

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bash_profile dosyasına ekleyin.

        echo "export TABLESTORE_ACCESS_KEY_ID='YOUR_STS_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export TABLESTORE_ACCESS_KEY_SECRET='YOUR_STS_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        echo "export TABLESTORE_SESSION_TOKEN='YOUR_STS_TOKEN'" >> ~/.bash_profile
      2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın:

        source ~/.bash_profile
      3. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

        echo $TABLESTORE_ACCESS_KEY_ID
        echo $TABLESTORE_ACCESS_KEY_SECRET
        echo $TABLESTORE_SESSION_TOKEN

    Windows

    CMD

    1. CMD'de ortam değişkenlerini ayarlamak için aşağıdaki komutları çalıştırın.

      setx TABLESTORE_ACCESS_KEY_ID "YOUR_STS_ACCESS_KEY_ID"
      setx TABLESTORE_ACCESS_KEY_SECRET "YOUR_STS_ACCESS_KEY_SECRET"
      setx TABLESTORE_SESSION_TOKEN "YOUR_STS_TOKEN"
    2. CMD'yi yeniden başlattıktan sonra ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      echo %TABLESTORE_ACCESS_KEY_ID%
      echo %TABLESTORE_ACCESS_KEY_SECRET%
      echo %TABLESTORE_SESSION_TOKEN%

    PowerShell

    1. PowerShell'de aşağıdaki komutu çalıştırın:

      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", "YOUR_STS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", "YOUR_STS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", "YOUR_STS_TOKEN", [EnvironmentVariableTarget]::User)
    2. Ortam değişkenlerinin etkili olup olmadığını kontrol etmek için aşağıdaki komutları çalıştırın:

      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("TABLESTORE_SESSION_TOKEN", [EnvironmentVariableTarget]::User)
  4. Kullandığınız programlama dili için Tablestore SDK'yı yükleyin.

    Java

    Maven kullanıyorsanız projenizin pom.xml dosyasına aşağıdaki bağımlılığı ekleyin:

    <dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>tablestore</artifactId> <version>5.17.4</version> </dependency>

    Daha fazla bilgi için bkz. Java için Tablestore SDK'yı yükleme.

    Go

    Proje dizininde go.mod dosyasını oluşturmak için go mod init <DIRNAME> komutunu çalıştırın. Ardından Go için Tablestore SDK'yı yüklemek için aşağıdaki komutu çalıştırın:

    Not

    <DIRNAME> proje dizini yolunu belirtir. <DIRNAME> ifadesini gerçek proje dizini yoluyla değiştirin.

    go get github.com/aliyun/aliyun-tablestore-go-sdk/tablestore

    Daha fazla bilgi için bkz. Go için Tablestore SDK'yı yükleme.

    Python

    Python için Tablestore SDK'yı pip ile yüklemek için aşağıdaki komutu çalıştırın:

    sudo pip install tablestore

    Daha fazla bilgi için bkz. Python için Tablestore SDK'yı yükleme.

    Node.js

    Node.js için Tablestore SDK'yı yüklemek için aşağıdaki komutu çalıştırın:

    npm install tablestore

    Daha fazla bilgi için bkz. Node.js için Tablestore SDK'yı yükleme.

    .NET

    Ayrıntılar için bkz. .NET için Tablestore SDK'yı yükleme.

    PHP

    Ayrıntılar için bkz. PHP için Tablestore SDK'yı yükleme.

Geniş tablo modeli

Geniş tablo modelini kullanırken geniş tablo istemcisini STS geçici kimlik bilgileriyle başlatın ve istek gönderin.

Java

V4 imza (önerilen)

Aşağıdaki Java örnek kodu, V4 imza kullanarak bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

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 imza

Aşağıdaki Java örnek kodu, V2 imza kullanarak bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

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

Aşağıdaki Go örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

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

Aşağıdaki Python örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

# -*- 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

Aşağıdaki Node.js örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

// 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

Aşağıdaki PHP örnek kodu bir istemci başlatır ve örnekteki tüm tablo adlarını listeler.

<?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);

Zaman serisi modeli

Zaman serisi modelini kullanırken zaman serisi istemcisini STS geçici kimlik bilgileriyle başlatın ve istek gönderin. Zaman serisi modeli Java, Go ve Python'da desteklenir.

Java

V4 imza (önerilen)

Aşağıdaki Java örnek kodu, V4 imza kullanarak bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.

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 imza

Aşağıdaki Java örnek kodu, V2 imza kullanarak bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.

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

Aşağıdaki Go örnek kodu bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.

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

Aşağıdaki Python örnek kodu bir istemci başlatır ve örnekteki tüm zaman serisi tablo adlarını listeler.

# -*- 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)

SSS

S: You are not authorized to do this action. You should be authorized by RAM. hatasını nasıl çözerim?

Bir RAM kullanıcısı kullanarak bir RAM rolünü üstlendiğinizde ve geçici kimlik bilgilerini aldığınızda RAM kullanıcısının AccessKey çiftini (AccessKey ID ve AccessKey secret) kullanmanız gerekir. Alibaba Cloud hesabının AccessKey çiftini kullanmayın.

S: The Min/Max value of DurationSeconds is 15min/1hr. hatasını nasıl çözerim?

Bu hata, geçici kimlik bilgisinin geçerlilik süresinin izin verilen aralığı aşması durumunda oluşur. Aşağıdaki kuralları uygulayın:

  • Rolün maksimum oturum süresini özelleştirmediyseniz varsayılan değer 3600 saniyedir. Bu durumda durationSeconds için minimum değer 900 saniye, maksimum değer ise 3600 saniyedir.

  • Rolün maksimum oturum süresini özelleştirdiyseniz durationSeconds için minimum değer 900 saniye, maksimum değer ise rolün maksimum oturum süresidir. Rolün maksimum oturum süresi 3600 ile 43200 saniye arasında ayarlanabilir.

Rolün maksimum oturum süresini RAM konsolunda görüntüleyebilirsiniz.

S: The security token you provided is invalid. hatasını nasıl çözerim?

SecurityToken değerini eksiksiz girdiğinizden emin olun ve ortam değişkenlerinizin doğru yapılandırıldığını doğrulayın.

S: Aynı anda birden çok geçici kimlik bilgisi alabilir miyim?

Evet. Her istek bir geçici kimlik bilgisi döndürür. Birden çok kimlik bilgisi almak için birden çok istek gönderin. Alınan tüm kimlik bilgilerini geçerlilik süreleri boyunca eşzamanlı olarak kullanabilirsiniz.

S: SDK kullanarak Tablestore hizmetine erişirken Request denied by instance ACL policies istisnası alırsam ne yapmalıyım?

İstemcinizin kullandığı ağ türü örneğin ağ erişim gereksinimlerini karşılamıyor. Tablestore konsolunun Instance Management sayfasında Network Management sekmesine gidin ve Allowed Network Types ayarını yapılandırın. Daha fazla bilgi için bkz. SDK kullanarak Tablestore hizmetine erişirken "Request denied by instance ACL policies" istisnalarını giderme.