You can create a RAM role for an Elastic Compute Service (ECS) instance. This way, applications on the ECS instance can access Key Management Service (KMS) by using a temporary Security Token Service (STS) credential and SDKs.

Step 1: Create a RAM role and attach a permission policy to the role

  1. Create a RAM role.
    Use OpenAPI Developer Portal to call the CreateRole operation of RAM to create the RAM role EcsRamRoleTest. Specify the following request parameters for the operation:
    • RoleName: the name of the RAM role. In this example, the RAM role is EcsRamRoleTest.
    • AssumeRolePolicyDocument: Enter the following policy, which indicates that ECS instances can assume this RAM role:
      {
          "Statement": [
              {
                  "Action": "sts:AssumeRole", 
                  "Effect": "Allow", 
                  "Principal": {
                      "Service": [
                          "ecs.aliyuncs.com"
                      ]
                  }
              }
          ], 
          "Version": "1"
      }
  2. Grant the RAM role the permission to access KMS.
    Use OpenAPI Developer Portal to call the AttachPolicyToRole operation of RAM to attach the system policy AliyunKMSFullAccess to the RAM role EcsRamRoleTest. Specify the following request parameters for the operation:
    • PolicyType: the type of the policy. Set this parameter to System, which indicates a system policy.
    • PolicyName: the name of the KMS system policy. In this example, the system policy is AliyunKMSFullAccess.
    • RoleName: the name of the RAM role. In this example, the RAM role is EcsRamRoleTest.

Step 2: Assign the RAM role to an ECS instance

You can use one of the following methods to assign the RAM role to an ECS instance:
  • Assign the RAM role to an existing ECS instance.

    Use OpenAPI Developer Portal to call the AttachInstanceRamRole operation of ECS instances to assign the RAM role to an existing ECS instance in a Virtual Private Cloud (VPC). Specify the following request parameters for the operation:

    • RegionId: the ID of the region where the ECS instance resides.
    • RamRoleName: the name of the RAM role. In this example, the RAM role is EcsRamRoleTest.
    • InstanceIds: the ID of the ECS instance in the VPC. Set this parameter to a value in the ["i-bXXXXXXXX"] format.
  • Specify the RAM role when you create an ECS instance.
    1. Create an instance.
      Use OpenAPI Developer Portal to call the CreateInstance operation of ECS to create an ECS instance. Specify the following request parameters for the operation:
      • RegionId: the ID of the region where the instance resides. In this example, the region ID is cn-hangzhou.
      • ImageId: the ID of the image used by the instance. In this example, the image ID is centos_7_03_64_40G_alibase_20170503.vhd.
      • InstanceType: the type of the instance. In this example, the type is ecs.g6.large.
      • VSwitchId: the ID of the vSwitch in the VPC where the instance resides.
        Note You can assign RAM roles only to ECS instances in VPCs. Therefore, this parameter is required.
      • RamRoleName: the name of the RAM role. In this example, the RAM role is EcsRamRoleTest.

      You can also authorize a RAM user to use the RAM role. For more information, see Use an instance RAM role by calling API operations.

    2. Configure the password and start the instance.
    3. Configure the instance to access the Internet in the ECS console or by calling an API operation.

Step 3: (Optional) Obtain a temporary authorization token

You can obtain a temporary authorization token for the RAM role. You can use the permissions and resources granted to the RAM role by using this periodically updated token. To obtain a temporary authorization token, perform the following steps:

  1. Query the temporary authorization token of the RAM role EcsRamRoleTest.
    • Linux instance: Run the http://100.100.100.200/latest/meta-data/ram/security-credentials/EcsRamRoleTest command.
    • Windows instance: For more information, see Overview.
  2. Obtain the temporary authorization token.
    Sample success response:
    {
       "AccessKeyId" : "STS.J8XXXXXXXXXX4",
       "AccessKeySecret" : "9PjfXXXXXXXXXBf2XAW",
       "Expiration" : "2017-06-09T09:17:19Z",
       "SecurityToken" : "CAIXXXXXXXXXXXwmBkleCTkyI+",
       "LastUpdated" : "2017-06-09T03:17:18Z",
       "Code" : "Success"
    }

Step 4: Access KMS by using an SDK

You can use an SDK to access KMS in one of the following methods:

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 RAM role.
        String roleName = "<your-ecs-ram-role-name>"; // In this example, "EcsRamRoleTest" is used.

        // Configure the credential provider of the RAM role.
        AlibabaCloudCredentialsProvider provider = new InstanceProfileCredentialsProvider(roleName);

        IAcsClient kmsClient = new DefaultAcsClient(profile, provider);

        EncryptRequest request = new EncryptRequest();

        // Specify the CMK alias or CMK ID that is used to encrypt "Hello world".
        request.setKeyId("alias/Apollo/SalaryEncryptionKey");
        request.setPlaintext("Hello world");

        try {
            EncryptResponse 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());
        }
    }
}
package com.aliyun.encryptionsdk.examples.credentials;
 
 import com.aliyun.encryptionsdk.AliyunConfig;
 import com.aliyun.encryptionsdk.AliyunCrypto;
 import com.aliyun.encryptionsdk.exception.InvalidAlgorithmException;
 import com.aliyun.encryptionsdk.exception.UnFoundDataKeyException;
 import com.aliyun.encryptionsdk.model.CryptoResult;
 import com.aliyun.encryptionsdk.provider.dataKey.DefaultDataKeyProvider;
 
 import java.util.Collections;
 
 import static org.junit.Assert.assertArrayEquals;
 
 /**
  *
  * Authenticate an ECS instance based on a RAM role.
  */
 public class EcsRamRoleSample {
     private static final String PLAIN_TEXT = "this is test.";
     private static final String cmkArn = "acs:kms:RegionId:UserId:key/CmkId";
     private static final String ecRamRoleName = "EcsRamRoleTest";
     public static void main(String[] args) {
         AliyunConfig config = new AliyunConfig();
         // Specify the RAM role.
         config.withEcsRamRole(ecRamRoleName);
         
         AliyunCrypto crypto = new AliyunCrypto(config);
         
         DefaultDataKeyProvider defaultDataKeyProvider = new DefaultDataKeyProvider(cmkArn);
         try {
             CryptoResult<byte[]> encryptResult = crypto.encrypt(defaultDataKeyProvider, PLAIN_TEXT.getBytes(), Collections.singletonMap("sample", "Context"));
             CryptoResult<byte[]> decryptResult = crypto.decrypt(defaultDataKeyProvider, encryptResult.getResult());
             assertArrayEquals(decryptResult.getResult(), PLAIN_TEXT.getBytes());
         } catch (InvalidAlgorithmException | UnFoundDataKeyException e) {
             System.out.println("Failed.");
             System.out.println("Error message: " + e.getMessage());
         }
     }
 }

Note: For more information about the complete sample code, see EcsRamRoleSample.java.

package com.aliyuncs.kms.secretsmanager.examples;
 
 import com.alibaba.fastjson.JSONObject;
 import com.aliyuncs.auth.InstanceProfileCredentialsProvider;
 import com.aliyuncs.kms.secretsmanager.cacheclient.exception.CacheSecretException;
 import com.aliyuncs.kms.secretsmanager.cacheclient.model.SecretInfo;
 import com.aliyuncs.kms.secretsmanager.cacheclient.service.DefaultSecretManagerClientBuilder;
 
 public class EcsSamples {
 
     public static void main(String[] args) throws CacheSecretException {
         String secretName = "<secret-name>";
         String roleName = "<your-ecs-ram-role-name>";
         String regionId = "<region-id>";
         SecretCacheClient client = SecretCacheClientBuilder.newCacheClientBuilder(
                 DefaultSecretManagerClientBuilder.standard().withCredentialsProvider(new InstanceProfileCredentialsProvider(roleName)).withRegion(regionId)
                         .build()
         ).build();
         SecretInfo secretInfo = client.getSecretInfo(secretName);
         System.out.println("secretInfo:"+JSONObject.toJSONString(secretInfo));
     }
 }