Resource Access Management (RAM) roles in Alibaba Cloud are analogous to temporary access badges issued to visitors at a company. A RAM role allows a user to assume a temporary identity to perform management actions within a specific scope. This is useful for scenarios such as cross-account access, role-based single sign-on (SSO), and temporary authorization.
Use cases
This topic uses a common cross-account access scenario to demonstrate the process. For example, assume your company runs an e-commerce website that is deployed on Alibaba Cloud Elastic Compute Service (ECS). Your IT department handles daily operations and maintenance (O&M). Occasionally, you may need assistance from external partners for specific technical issues or special maintenance tasks. To maintain the security of your cloud resources, you do not want to share long-term credentials, such as an Alibaba Cloud account or a RAM user, with external partners.
The following diagram illustrates how to use a RAM role to grant cross-account access permissions:
Account A: Your company's Alibaba Cloud account.
Account B: Your external partner's Alibaba Cloud account.
Account A creates a RAM role and grants Account B permission to assume the role.
Account B creates a RAM user and grants the user permission to assume the role.
The RAM user of Account B assumes the RAM role of Account A to manage the resources of Account A.
Procedure
Create a RAM role and grant permissions in Account A
1. Create a RAM role
Log on to the RAM console using Account A. Create a RAM role and set the trusted entity to an Alibaba Cloud account. On the Create Role page, for Principal Name, select Other Account and enter the UID of Account B. For more information, see Create a RAM role for a trusted Alibaba Cloud account.
2. Grant permissions to the RAM role
Create an access policy that allows users to view instance information and log on to ECS instances using Workbench. Then, attach the access policy to the RAM role. For more information, see Create custom policies.
Create a RAM user and grant permissions in Account B
1. Create a RAM user
Log on to the RAM console using Account B. Create a RAM user. When you create the RAM user, select Console Access and Using permanent AccessKey to access. For more information, see Create a RAM user.
2. Grant permissions to the RAM user
Before a RAM user can assume a RAM role, you must grant the required permissions to the user. Use Account B to attach the AliyunSTSAssumeRoleAccess policy to the RAM user. This policy allows the RAM user to assume all RAM roles. For more information, see Grant permissions to a RAM user.
To allow the RAM user to assume only a specific RAM role, see Can I specify the RAM role that a RAM user can assume?
Assume a RAM role
Console
Log on to the RAM user logon page using the RAM user that you created for Account B.
Hover over the profile picture in the upper-right corner and click Switch Identity.
On the Switch Role page, enter the required information and click Submit. In this example, enter the UID of Account A and the name of the RAM role.
Verify the access permissions.
Log on to the ECS console and view information about the Alibaba Cloud ECS instances.
Verification 1: The RAM user can assume the RAM role of Account A to view ECS instance information and can also log on to the instance using the remote connection tool Workbench.
Verification 2: When Account A revokes the authorization, the RAM user can no longer view the ECS instance information of Account A.
API
You can also access the resources of Account A using program code. The general process is as follows:
Set a system environment variable to the AccessKey that you obtained when you created the RAM user for Account B. The method for setting environment variables varies by operating system. For more information, see Configure environment variables in Linux, macOS, and Windows.
Use the RAM user of Account B to call the
AssumeRoleAPI. Pass the ARN of the RAM role of Account A to obtain a temporary Security Token Service (STS) token.Use the obtained STS token to call the APIs of the relevant Alibaba Cloud service to view the cloud resources of Account A.
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 that belong 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
RAM is an Alibaba Cloud service that you can use to manage user identities and resource access permissions. For more information, see What is RAM?
For more information about how a RAM user can assume a RAM role, see Assume a RAM role.
For more information about role-based SSO, see Role-based SSO.