Similar to temporary badges that grant visitors limited access within a building, Resource Access Management (RAM) roles provided by Alibaba Cloud enable users to assume temporary identities and perform operations within authorized scopes. RAM roles are suitable for cross-account access, role-based single sign-on (SSO), and temporary authorization scenarios.
Scenarios
You can use a RAM role to authorize cross-account access. For example, your company runs an e-commerce website hosted on Alibaba Cloud Elastic Compute Service (ECS). The IT department performs routine maintenance on the website and may engage external partners for specific technical support or maintenance tasks. To provide cloud resource security, we do not recommend sharing long-term accounts, such as Alibaba Cloud accounts and RAM users, with external partners.
The following figure shows a flowchart for authorizing cross-account access by using a RAM role.
Account A: the Alibaba Cloud account of your company.
Account B: the Alibaba Cloud account of an external partner.
Account A creates a RAM role and grants permissions to Account B to assume the role.
Account B creates a RAM user and grants permissions to the user to assume the role.
The RAM user of Account B assumes the RAM role of Account A to perform operations on the resources of Account A.
Procedure
Account A creates a RAM role and grants permissions to the role
1. Create a RAM role
Log on to the RAM console by using Account A and create a RAM role. When you create a RAM role, set the Select Trusted Entity parameter to Alibaba Cloud Account Then, in the Select Alibaba Cloud Account section, select Other Alibaba Cloud Account and enter the UID of Account B. For more information about how to create a RAM role, see Create a RAM role for a trusted Alibaba Cloud account.
2. Grant permissions to the RAM role
Create a policy that grants permissions to view information about ECS instances and log on to ECS instances by using Workbench. Then, attach the policy to the RAM role. For more information, see Create custom policies.
Account B creates a RAM user and grants permissions to the user
1. Create a RAM user
Log on to the RAM console by using Account B and create a RAM user. When you create the RAM user, set the Access Mode parameter to Console Access and Using permanent AccessKey to access. For more information, see Create a RAM user.
2. Grant permissions to the RAM user
To assume a RAM role, the RAM user must have the required permissions. Account B must attach the AliyunSTSAssumeRoleAccess
policy to the RAM user. This policy grants permissions to the RAM user to assume all RAM roles. For more information, see Grant permissions to a RAM user.
You can configure the RAM user to assume only a specific RAM role. For more information, see Can I specify the RAM role that a RAM user can assume?
Assume a RAM role
Assume a RAM role in the consoles
Go to the RAM User Logon page and log on to the Alibaba Cloud Management Console by using the RAM user of Account B.
In the upper-right corner of the console, move the pointer over the profile picture and click Switch Identity.
On the Switch Role page, enter the required information and click Submit to log on. In this example, enter the UID of Account A and the RAM role name.
Check whether the required permissions are granted.
Log on to the ECS console and view ECS instance information.
1) Check whether the RAM user can assume the RAM role of Account A to view information about ECS instances of Account A and log on to the instances by using Workbench.
2) Check whether the RAM user can no longer view information about ECS instances of Account A after Account A revokes permissions.
Assume a RAM role by using program code
You can access the resources of Account A by using program code. Perform the following steps:
Configure the AccessKey pair of the RAM user of Account B in system environment variables. For information about how to configure an AccessKey pair in environment variables of different operating systems, see Configure environment variables in Linux, macOS, and Windows.
Use the RAM user of Account B to call the
AssumeRole
operation with the Alibaba Cloud Resource Name (ARN) of the RAM role of Account A to obtain a Security Token Service (STS) token.Use the STS token to call API operations to view 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 a set of temporary access credentials (STS token) and then use the STS token to access ECS resources.
*/
public class Sample {
public static void main(String[] args) {
// The endpoints in the following example are provided only for reference. Configure region-specific endpoints based on your business requirements.
String stsEndpoint = "sts.cn-shanghai.aliyuncs.com";
String ecsEndpoint = "ecs.cn-shanghai.aliyuncs.com";
// The region ID of the ECS instance. In this example, the region ID is cn-shanghai.
String regionId = "cn-shanghai";
// The ARN of the RAM role.
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 an API operation to view cloud resources of Account A.
accessResources(assumeRoleResponse, ecsEndpoint, regionId);
}
/**
* Use the temporary access credentials to access cloud resources.
*
* @param assumeRoleResponse The response object that contains temporary access credentials.
*/
private static void accessResources(AssumeRoleResponse assumeRoleResponse, String ecsEndpoint, String regionId) {
try {
// Extract 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 operation and obtain 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 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") Obtain the AccessKey ID from the environment variable.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") Obtain the AccessKey secret from the environment variable.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = stsEndpoint;
Client client = new Client(config);
// Create an AssumeRole request object in which the ARN of the RAM role to be assumed and the role session name are configured.
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 in the China (Shanghai) region in Account A.
{
"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",
...
// Specific parameters are not displayed.
...
"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 about RAM, see What is RAM?
For information about how to use a RAM user to assume a RAM role, see Assume a RAM role.
For information about role-based SSO, see Role-based SSO.