All Products
Search
Document Center

Key Management Service:Use an instance RAM role to access KMS

Last Updated:Aug 25, 2026

An instance RAM role allows an ECS instance to assume a role with specific permissions. If your self-managed application is deployed on an Alibaba Cloud ECS instance, you can use an instance RAM role to access KMS without hardcoding access credentials. This topic describes how to use an instance RAM role to access KMS.

Scope

  • Alibaba Cloud SDK: Used to perform control plane operations.

  • Credentials SDK: Includes the Secrets Manager Client, Secrets Manager JDBC Client, and RAM secret plug-in. Used to retrieve secret values.

Prerequisites

  • The ECS instance is in a VPC.

  • Only one RAM role can be attached to an ECS instance at a time.

  • If you are a RAM user, request the required permissions from your Alibaba Cloud account administrator to configure RAM roles. For more information, see instance RAM roles.

Step 1: Create a RAM role and grant permissions

RAM console

  1. Create a RAM role and set its trusted entity to an Alibaba Cloud service.

    1. Log on to the RAM console.

    2. In the navigation pane on the left, choose Identities > Roles.

    3. On the Roles page, click Create Role and follow the on-screen instructions. Configure the following parameters and set others as needed.

      • Role name: This topic uses EcsRamRoleTest as an example.

      • Trusted entity type: Select Alibaba Cloud Service.

      • Select trusted service: Select ECS.

  2. Grant the RAM role permissions to access KMS.

    By default, a new RAM role has no permissions. You must grant permissions to the role.

    1. On the Identities > Roles page, click Attach Policy in the Actions column of the target RAM role.

    2. In the Attach Policy panel, select System Policy, search for and select AliyunKMSFullAccess, and then click OK.

RAM API

  1. Create a RAM role and set its trusted entity to an Alibaba Cloud service.

    Call the CreateRole API operation of RAM with the following parameters:

    • RoleName: Enter a name for the RAM role. This topic uses EcsRamRoleTest as an example.

    • AssumeRolePolicyDocument: Use the following policy document to allow ECS to assume this role.

      {
          "Statement": [
              {
                  "Action": "sts:AssumeRole", 
                  "Effect": "Allow", 
                  "Principal": {
                      "Service": [
                          "ecs.aliyuncs.com"
                      ]
                  }
              }
          ], 
          "Version": "1"
      }
  2. Grant the RAM role permissions to access KMS.

    Call the AttachPolicyToRole API operation of RAM to attach the AliyunKMSFullAccess System Policy to the EcsRamRoleTest instance RAM role. Set the following parameters:

    • PolicyType: Set to System to indicate a System Policy.

    • PolicyName: Set to AliyunKMSFullAccess.

    • RoleName: Set to the name of the RAM role, such as EcsRamRoleTest.

Step 2: Attach the RAM role to an ECS instance

ECS console

Note

If you have not purchased an ECS instance, purchase one first. For more information, see Create an instance on the custom launch tab.

  1. Log on to the ECS console.

  2. In the navigation pane on the left, choose Instances & Images> Instances.

  3. In the top navigation bar, select the region and resource group where your ECS instance is located.

  4. Find the target ECS instance, and in the Actions column, choose 图标>Instance Settings>Attach/Detach RAM Role.

  5. In the dialog box that appears, select the RAM role you created and click OK.

ECS API

  • Attach an instance RAM role to an existing ECS instance

    Call the AttachInstanceRamRole API operation of ECS to attach an instance RAM role to an existing ECS instance in a VPC. Set the following parameters:

    • RegionId: The ID of the region where the instance is located.

    • RamRoleName: The name of the RAM role, such as EcsRamRoleTest.

    • InstanceIds: The ID of the ECS instance, such as ["i-bXXXXXXXX"].

  • Specify an instance RAM role when you create an ECS instance

    1. Create an instance.

      Call the CreateInstance API operation of ECS. Set the following parameters:

      • RegionId: The ID of the region where the instance is located.

      • ImageId: The ID of the image for the instance. Example: centos_7_03_64_40G_alibase_****.vhd.

      • InstanceType: The instance type. Example: ecs.g6.large.

      • VSwitchId: The ID of the vSwitch in the VPC where the instance resides.

        Note

        instance RAM roles are supported only for ECS instances in a VPC. This parameter is required.

      • RamRoleName: The name of the instance RAM role, such as EcsRamRoleTest.

      You can also authorize a RAM user to use an instance RAM role. For more information, see instance RAM roles.

    2. Call the ModifyInstanceVncPasswd and StartInstance API operations of ECS to set a password for the instance and start it.

Step 3: Access KMS with the RAM role

This section provides a Java example of how to call the KMS ListKeys API operation to list all key IDs in the current region. For more detailed SDK guidance, see SDK reference.

Alibaba Cloud SDK V2.0

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        com.aliyun.credentials.models.Config credentialConfig = new com.aliyun.credentials.models.Config();
        // Set the credential type.
        credentialConfig.type = "ecs_ram_role";
        // Optional. To reduce API calls, specify the instance RAM role name. If this parameter is omitted, the role name is retrieved automatically.
        credentialConfig.roleName = "<your-ecsRamRoleName>";
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialConfig);

        com.aliyun.teaopenapi.models.Config kmsClientConfig = new com.aliyun.teaopenapi.models.Config()
        // Set the KMS endpoint. Example: kms.cn-hangzhou.aliyuncs.com
        .setEndpoint( "kms.cn-hangzhou.aliyuncs.com").
                setCredential(credentialClient);
        return new com.aliyun.kms20160120.Client(kmsClientConfig);

    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.ListKeysRequest listKeysRequest = new com.aliyun.kms20160120.models.ListKeysRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            client.listKeysWithOptions(listKeysRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            _error.printStackTrace();
        }        
    }
}

Tab body

Secrets Manager Client

For more information, see Secrets Manager Client.

  1. Configure the following parameters in the secretsmanager.properties file or as system environment variables.

    Parameter

    Value

    credentials_type

    Set to ecs_ram_role.

    credentials_role_session_name

    A custom name for the role session, used for auditing.

    cache_client_region_id

    The format is [{"regionId":"<your region id>"}]. Replace <your region id> with your actual region ID.

  2. Build the client to retrieve the secret value.

    import com.aliyuncs.kms.secretsmanager.client.v2.SecretCacheClient;
    import com.aliyuncs.kms.secretsmanager.client.v2.SecretCacheClientBuilder;
    import com.aliyuncs.kms.secretsmanager.client.v2.exception.CacheSecretException;
    import com.aliyuncs.kms.secretsmanager.client.v2.model.SecretInfo;
    
    public class CacheClientEnvironmentSample {
    
        public static void main(String[] args) {
            try {
                SecretCacheClient client = SecretCacheClientBuilder.newClient();
                SecretInfo secretInfo = client.getSecretInfo("#secretName#");
                System.out.println(secretInfo);
            } catch (CacheSecretException e) {
                e.printStackTrace();
            }
        }
    }

Secrets Manager JDBC Client

This section uses a MySQL database connection over JDBC as an example. For more information, see Secrets Manager JDBC Client.

  1. In your project's application code, add a configuration file named secretsmanager.properties.

    ## Type of access credentials
    credentials_type=ecs_ram_role
    ## Name of the ECS RAM role
    credentials_role_name=#credentials_role_name#
    ## Region of the associated KMS instance
    cache_client_region_id=[{"regionId":"#regionId#"}]
    ## Custom refresh interval. Unit: milliseconds. Default: 6 hours. Minimum: 5 minutes.
    refresh_secret_ttl=21600000
  2. Connect to the MySQL database over JDBC.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class SecretManagerJDBCSample {
        public static void main(String[] args) throws Exception {
            // Load the Alibaba Cloud Secrets Manager JDBC driver com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver
            Class.forName("com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver");
            Connection connect = null;
            try {
                connect = DriverManager.getConnection("secrets-manager:mysql://<YOUR-MYSQL-IP>:<YOUR-MYSQL-PORT>/<YOUR-DATABASE-NAME>", "#your-mysql-secret-name#","");
            } catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }

RAM secret plug-in

For more information, see RAM secret plug-in.

  1. Add the configuration file managed_credentials_providers.properties to the runtime code of your project.

    credentials_type=ecs_ram_role
    ## Name of the ECS RAM role
    credentials_role_name=#credentials_role_name#
    ## Region of the associated KMS instance
    cache_client_region_id=[{"regionId":"#regionId#"}]
  2. Obtain an Alibaba Cloud SDK for Java client and call cloud services.

    The following example shows how to call the DescribeInstanceStatus operation of ECS:

    Note

    Before you run the sample code, add the aliyun-java-sdk-ecs dependency to your pom.xml file.

    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusRequest;
    import com.aliyuncs.ecs.model.v20140526.DescribeInstanceStatusResponse;
    import com.aliyun.kms.secretsmanager.plugin.sdkcore.ProxyAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    
    public class AliyunSdkProviderSample {
        public static void main(String[]args) {
            String secretName="******";
            /*
              If the application cannot read the default configuration file (managed_credentials_providers.properties) from the classpath or an executable JAR file, or if you need to use a custom configuration file name, you can call the following code to specify a custom configuration file. The file is read in the following order:
              1. If "your-config-name" is an absolute path, the file is read from that path.
              2. If "your-config-name" is only a file name, the file is read from the classpath first, and then from the executable JAR file.
            */
            //ConfigLoader.setConfigName("your-config-name");
            
            // 1. Obtain an IAcsClient by using aliyun-java-sdk-managed-credentials-provider.
            IAcsClient client = null;
            try {
                client = new ProxyAcsClient("<the regionId of ECS>", secretName);
            } catch (ClientException e) {
                 e.printStackTrace();
             }
            // 2. Call an ECS API operation to implement your business logic.
            DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();
            DescribeInstanceStatusResponse response;
            try {
                 response = client.getAcsResponse(request);
            } catch (ServerException e) {
                 e.printStackTrace();
             } catch (ClientException e) {
                 e.printStackTrace();
             }
            // 3. Shut down the client to release resources used by the plug-in.
            client.shutdown();
        }
    }

Alibaba Cloud SDK V1.0 (Not Recommended)

package com.aliyuncs.kms.examples;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.AlibabaCloudCredentialsProvider;
import com.aliyuncs.auth.InstanceProfileCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.kms.model.v20160120.*;
import com.aliyuncs.profile.DefaultProfile;

public class RamRoleTest {
    public static void main(final String[] args) throws Exception {
        String regionId = "<region-id>";
        DefaultProfile profile = DefaultProfile.getProfile(regionId);

        // Set the RAM role. This topic uses EcsRamRoleTest as an example.
        String roleName = "EcsRamRoleTest"; 

        // Create the credentials provider for the instance RAM role.
        AlibabaCloudCredentialsProvider provider = new InstanceProfileCredentialsProvider(roleName);

        IAcsClient client = new DefaultAcsClient(profile, provider);

        ListKeysRequest request = new ListKeysRequest();
      
        try {
            ListKeysResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }
}

References