All Products
Search
Document Center

Elastic Compute Service:Control ECS access with RAM roles

Last Updated:May 15, 2026

Grant scoped, temporary access to ECS resources across accounts by assuming RAM roles.

Use cases

Suppose your company runs an e-commerce site on ECS. Your IT department handles daily O&M, but occasionally external partners need access for specific maintenance tasks. Instead of sharing long-term credentials such as an Alibaba Cloud account or RAM user, you can use RAM roles to grant temporary, scoped access.

The following diagram illustrates cross-account access with a RAM role:

image

Account A: Your company's Alibaba Cloud account.

Account B: Your external partner's Alibaba Cloud account.

  1. Account A creates a RAM role and authorizes Account B to assume it.

  2. Account B creates a RAM user and grants it permission to assume the role.

  3. Account B's RAM user assumes Account A's RAM role to manage Account A's resources.

Procedure

Create a RAM role and grant permissions in Account A

1. Create a RAM role

Log on to the RAM console with Account A. Create a RAM role with the trusted entity set to an Alibaba Cloud account. For Principal Name, select Other Account and enter the UID of Account B. See Create a RAM role for an Alibaba Cloud account.

2. Grant permissions to the RAM role

Create a policy that allows viewing instance information and logging on to ECS instances with Workbench, then attach it to the RAM role. See Create a custom policy.

Temporary access policy for role assumption by visitors

This policy grants permission to view ECS instance information and log on to instances with Workbench.

{
    "Version": "1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:List*",
                "ecs:Describe*",
                "ecs-workbench:LoginInstance"
            ],
            "Resource": "*"
        }
    ]
}

Create a RAM user and grant permissions in Account B

1. Create a RAM user

Log on to the RAM console with Account B. Create a RAM user and select Console Access and Using permanent AccessKey to access. See Create a RAM user.

2. Grant permissions to the RAM user

Attach the AliyunSTSAssumeRoleAccess policy to the RAM user under Account B. This policy allows the RAM user to assume all RAM roles. See Grant permissions to a RAM user.

To restrict the user to a specific role, see Can I specify the RAM role that a RAM user can assume?

Assume a RAM role

Console

  1. Log on to the RAM user logon page with Account B's RAM user.

  2. Hover over the profile picture in the upper-right corner and click Switch Identity.

  3. On the Switch Role page, enter the UID of Account A and the RAM role name, then click OK.

  4. Verify the access permissions.

    Log on to the ECS console and verify that you can view ECS instance information.

    Verification 1: The RAM user can view ECS instance information and log on to instances with Workbench.

    Verification 2: After Account A revokes the authorization, the RAM user can no longer view Account A's ECS instance information.

API

You can also access Account A's resources programmatically:

  1. Set a system environment variable to the AccessKey obtained when creating Account B's RAM user. The method varies by operating system. See Configure environment variables in Linux, macOS, and Windows.

  2. Call the AssumeRole API with Account B's RAM user. Pass the ARN of Account A's RAM role to obtain a temporary STS token.

  3. Use the STS token to call the APIs of the target Alibaba Cloud service to access Account A's resources.

Java sample code

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>ecs20140526</artifactId>
  <version>5.4.4</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>sts20150401</artifactId>
  <version>1.1.4</version>
</dependency>
<dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>credentials-java</artifactId>
   <version>0.3.10</version>
</dependency>
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;

/**
 * Assume a RAM role to obtain temporary access credentials, and then use these credentials to access ECS resources.
 */
public class Sample {
    public static void main(String[] args) {
        // This is for demonstration purposes only. Select a region-specific endpoint based on your actual business needs.
        String stsEndpoint = "sts.cn-shanghai.aliyuncs.com";
        String ecsEndpoint = "ecs.cn-shanghai.aliyuncs.com";
        // Query the information of ECS instances in cn-shanghai.
        String regionId = "cn-shanghai";
        // The ARN of the RAM role to be assumed.
        String ramRoleArn = "acs:ram::14************16:role/cooperativepartnerrole";

        // Use the RAM user of Account B to assume the RAM role of Account A and obtain temporary access credentials.
        AssumeRoleResponse assumeRoleResponse = playRamRole(stsEndpoint, ramRoleArn);
        // Call the API provided by the Alibaba Cloud service to view the cloud resources of Account A.
        accessResources(assumeRoleResponse, ecsEndpoint, regionId);
    }

    /**
     * Use temporary access credentials to access cloud resources.
     *
     * @param assumeRoleResponse The response object that contains the temporary access credentials.
     */
    private static void accessResources(AssumeRoleResponse assumeRoleResponse, String ecsEndpoint, String regionId) {
        try {
            // Extract the temporary access credential information.
            AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials assumeRoleResponseBodyCredentials = assumeRoleResponse.body.credentials;
            com.aliyun.credentials.models.Config credentialsConfig = new com.aliyun.credentials.models.Config()
                    .setType("sts") // The credential type.
                    .setAccessKeyId(assumeRoleResponseBodyCredentials.accessKeyId)
                    .setAccessKeySecret(assumeRoleResponseBodyCredentials.accessKeySecret)
                    .setSecurityToken(assumeRoleResponseBodyCredentials.securityToken);
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client(credentialsConfig);

            // Create an ECS client.
            Config ecsConfig = new Config()
                    .setEndpoint(ecsEndpoint)
                    .setCredential(credentialClient);
            com.aliyun.ecs20140526.Client ecsClient = new com.aliyun.ecs20140526.Client(ecsConfig);
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                    .setRegionId(regionId);
            RuntimeOptions runtimeOptions = new RuntimeOptions();

            // Call the DescribeInstances API and get the response.
            DescribeInstancesResponse response = ecsClient.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);
            // Print the response.
            System.out.println(new Gson().toJson(response.body));
        } catch (Exception e) {
            throw new RuntimeException("AccessResources failed: " + e.getMessage());
        }
    }

    /**
     * Assume a RAM role to obtain temporary access credentials.
     *
     * @return The response object that contains the temporary access credentials.
     */
    private static AssumeRoleResponse playRamRole(String stsEndpoint, String ramRoleArn) {
        try {
            // Create an StsClient object and call the assumeRole operation to obtain an STS token.
            Config config = new Config()
                    // System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") gets the value of AccessKey ID from the environment variable.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") gets the value of AccessKey secret from the environment variable.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            config.endpoint = stsEndpoint;
            Client client = new Client(config);
            // Create an AssumeRoleRequest object and specify the ARN of the RAM role to be assumed and the role session name.
            AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                    .setRoleArn(ramRoleArn)
                    .setRoleSessionName("CooperativePartner");
            RuntimeOptions runtime = new RuntimeOptions();
            return client.assumeRoleWithOptions(assumeRoleRequest, runtime);
        } catch (Exception e) {
            throw new RuntimeException("play RAM role failed: " + e.getMessage());
        }
    }
}

Result: The program returns a list of ECS resources belonging to Account A in the China (Shanghai) region.

{
    "instances":{
        "instance":[
            {
                "creationTime":"2024-10-23T09:12Z",
                "expiredTime":"2099-12-31T15:59Z",
                "hostName":"iZ********************pZ",
                "imageId":"m-uf****************jf",
                "instanceChargeType":"PostPaid",
                "instanceId":"i-uf****************ap",
                "instanceName":"launch-advisor-20241023-c6",
                "instanceNetworkType":"vpc",
                "instanceType":"ecs.c6.xlarge",
                ...
                // Some parameters are omitted.
                ...
                "vpcAttributes":{
                    "natIpAddress":"",
                    "privateIpAddress":{
                        "ipAddress":[
                            "17*.**.**.*15"
                        ]
                    },
                    "vSwitchId":"vsw-uf*****************tk",
                    "vpcId":"vpc-uf*****************kr"
                },
                "zoneId":"cn-shanghai-b"
            }
        ]
    },
    "nextToken":"",
    "pageNumber":1,
    "pageSize":10,
    "requestId":"C1468F7E********************7A3A712",
    "totalCount":1
}

References