Hardcoding credentials in application code creates real risks: credentials can leak through source control, are difficult to rotate at scale, and must be redistributed every time they change. Instance RAM roles eliminate these risks by giving your ECS instance a temporary, automatically rotated identity — your application gets KMS access without storing a single secret.
This guide walks you through three steps: creating an instance RAM role with KMS permissions, attaching it to your ECS instance, and using it to call KMS from your application.
Prerequisites
Before you begin, ensure that you have:
An ECS instance deployed in a virtual private cloud (VPC). Only one instance RAM role can be assigned to an ECS instance.
Permission to configure RAM roles. If you are a RAM user, ask the account owner to grant this permission. For details, see Instance RAM roles.
Choose an SDK
Select the SDK that matches your use case:
| SDK | Use when |
|---|---|
| Alibaba Cloud SDK | Managing KMS resources (keys, policies) |
| Secrets Manager Client | Reading secret values from Secrets Manager |
| Secret JDBC client | Connecting to a database using secrets stored in KMS |
| RAM secret plug-in | Injecting secrets into an existing Alibaba Cloud SDK client |
Quick selection guide:
If you are managing KMS keys or policies, use Alibaba Cloud SDK (V2.0 recommended).
If your application reads database credentials from KMS Secrets Manager, use Secret JDBC client.
If your application reads other types of secrets from KMS, use Secrets Manager Client.
If you want to add automatic credential rotation to an existing Alibaba Cloud SDK client without changing business logic, use RAM secret plug-in.
Step 1: Create an instance RAM role and grant permissions
Use the RAM console
Log on to the RAM console.
In the left navigation pane, choose Identities > Roles.
On the Roles page, click Create Role.
On the Create Role page, set Principal Type to Cloud Service, select Elastic Compute Service / ECS for Principal Name, and click OK.
Enter a role name. This topic uses EcsRamRoleTest as an example.
On the Roles page, find the role you just created and click Grant Permission in the Actions column.
In the Grant Permission panel, go to the System Policy tab, select AliyunKMSFullAccess, and click OK.
Call RAM API operations
Create the role — call CreateRole with the following parameters:
| Parameter | Value |
|---|---|
RoleName | EcsRamRoleTest |
AssumeRolePolicyDocument | See the policy document below |
{
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": [
"ecs.aliyuncs.com"
]
}
}
],
"Version": "1"
}Grant KMS access — call AttachPolicyToRole with the following parameters:
| Parameter | Value |
|---|---|
PolicyType | System |
PolicyName | AliyunKMSFullAccess |
RoleName | EcsRamRoleTest |
Step 2: Attach the instance RAM role to your ECS instance
Use the ECS console
If you do not have an ECS instance, create one first. See Create an instance on the Custom Launch tab.
Log on to the ECS console.
In the left navigation pane, choose Instances & Images > Instances.
In the top navigation bar, select the region and resource group.
Find the target ECS instance and choose  > Instance Settings > Attach/Detach RAM Role in the Actions column.
In the dialog box, select EcsRamRoleTest from the RAM Role drop-down list and click Confirm.
Call ECS API operations
Attach to an existing ECS instance — call AttachInstanceRamRole with the following parameters:
| Parameter | Value |
|---|---|
RegionId | Region ID of the ECS instance |
RamRoleName | EcsRamRoleTest |
InstanceIds | Instance ID in the format ["i-bXXXXXXXX"] |
Specify the role when creating a new ECS instance — call CreateInstance with the following parameters:
| Parameter | Value |
|---|---|
RegionId | Target region ID |
ImageId | centos_7_03_64_40G_alibase_****.vhd (example) |
InstanceType | ecs.g6.large (example) |
VSwitchId | vSwitch ID in the VPC (required — instance RAM roles are only supported on VPC instances) |
RamRoleName | EcsRamRoleTest |
After the instance is created, call ModifyInstanceVncPasswd to set a password, then call StartInstance to start it.
Step 3: Access KMS using the instance RAM role
The following examples show how to call the ListKeys API operation to list all keys in the current region. For the full SDK reference, see SDK references.
All examples use the ecs_ram_role credential type — the SDK automatically retrieves temporary credentials from the ECS instance metadata service without any hardcoded keys.
Alibaba Cloud SDK V1.0
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);
// Specify the instance RAM role name.
String roleName = "EcsRamRoleTest";
// Configure the credential provider to use 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());
}
}
}For credential management details, see Manage access credentials (Alibaba Cloud SDK V1.0).
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();
// Use the ECS instance RAM role as the credential type.
credentialConfig.type = "ecs_ram_role";
// Optional: specify the role name to reduce metadata service requests. If not set, the role name is automatically obtained.
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 for your region, for 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();
}
}
}For credential management details, see Manage access credentials (Alibaba Cloud SDK V2.0).
Secrets Manager Client
Configure credentials in system environment variables or in secretsmanager.properties:
| Parameter | Value |
|---|---|
credentials_type | ecs_ram_role |
credentials_role_session_name | Name of the RAM role |
cache_client_region_id | [{"regionId":"<your-region-id>"}] |
Then construct the client to retrieve secret values:
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClient;
import com.aliyuncs.kms.secretsmanager.client.SecretCacheClientBuilder;
import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException;
import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo;
public class CacheClientEnvironmentSample {
public static void main(String[] args) {
try {
// Build Secrets Manager Client using configuration from environment variables or secretsmanager.properties.
SecretCacheClient client = SecretCacheClientBuilder.newClient();
// Retrieve the secret value by secret name.
SecretInfo secretInfo = client.getSecretInfo("#secretName#");
System.out.println(secretInfo);
} catch (CacheSecretException e) {
e.printStackTrace();
}
}
}For the full reference, see Secret client.
Secret JDBC client
Add secretsmanager.properties to your project:
## Credential type for the ECS instance RAM role.
credentials_type=ecs_ram_role
## Name of the instance RAM role attached to your ECS instance.
credentials_role_name=#credentials_role_name#
## Region of the KMS instance.
cache_client_region_id=[{"regionId":"#regionId#"}]
## Secret rotation interval. Default: 21600000 ms (6 hours). Minimum: 300000 ms (5 minutes).
refresh_secret_ttl=21600000Connect to MySQL using the secret JDBC driver:
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 secret JDBC driver.
Class.forName("com.aliyun.kms.secretsmanager.MysqlSecretsManagerSimpleDriver");
Connection connect = null;
try {
// The driver retrieves MySQL credentials from KMS automatically.
connect = DriverManager.getConnection(
"secrets-manager:mysql://<YOUR-MYSQL-IP>:<YOUR-MYSQL-PORT>/<YOUR-DATABASE-NAME>",
"#your-mysql-secret-name#",
""
);
} catch (SQLException e) {
e.printStackTrace();
}
}
}For the full reference, see Secret JDBC client.
RAM secret plug-in
Add managed_credentials_providers.properties to your application's working directory:
credentials_type=ecs_ram_role
## Name of the instance RAM role attached to your ECS instance.
credentials_role_name=#credentials_role_name#
## Region of the KMS instance.
cache_client_region_id=[{"regionId":"#regionId#"}]If the application cannot read the default configuration file (managed_credentials_providers.properties) from the classpath or executable JAR, you can specify a custom file path usingConfigLoader.setConfigName("your-config-name"). If the value is set to an absolute path, the system reads the configuration file from that path. If it is set to a file name only, the system first checks the classpath and then the executable JAR package.
Add the aliyun-java-sdk-ecs dependency to your pom.xml, then create a ProxyAcsClient to call Alibaba Cloud APIs:
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 = "******";
// 1. Create a ProxyAcsClient backed by the RAM secret plug-in.
IAcsClient client = null;
try {
client = new ProxyAcsClient("<the regionId of ECS>", secretName);
} catch (ClientException e) {
e.printStackTrace();
}
// 2. Call an API operation — credentials are injected automatically.
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 plug-in resources.
client.shutdown();
}
}For the full reference, see RAM secret plug-in.