All Products
Search
Document Center

Function Compute (2.0):Grant permissions across Alibaba Cloud accounts by using RAM roles

Last Updated:Dec 01, 2023

This topic describes how to use the Resource Access Management (RAM) console or an SDK to grant permissions across Alibaba Cloud accounts by using a Security Token Service (STS) token. The authorized Alibaba Cloud accounts can view the resources of the authorizing accounts in Function Compute.

Scenarios

Enterprise A has activated Function Compute and requires Enterprise B to manage Function Compute resources. Enterprise A has the following requirements:

  • Enterprise A can focus on its business systems and act only as the owner of Function Compute resources. In addition, Enterprise A can authorize Enterprise B to manage resources, such as creating services and functions.

  • Enterprise A does not need to change permissions when an employee joins or leaves Enterprise B. Enterprise B can grant its RAM users fine-grained permissions on resources of Enterprise A.

  • Enterprise A can revoke the permissions that are granted to Enterprise B when the cooperation between Enterprise A and Enterprise B ends.

Use the RAM console

Assume Enterprise A wants to grant employees of Enterprise B the permission to access all services in Function Compute. Enterprise A has an Alibaba Cloud account named Account A, and Enterprise B has an Alibaba Cloud account named Account B.

  • The ID of Account A is 123456789012****, and the account alias is company-a.

  • The ID of Account B is 134567890123****, and the account alias is company-b.

Step 1: Create a RAM role by using Account A

Use Account A to create a RAM role, grant the required permissions to the RAM role, and then authorize Account B to assume this role. You must enter Account B in the Other Alibaba Cloud Account field.

  1. Use Account A to log on to the RAM console.

  2. In the left-side navigation pane, choose Identities > Roles.

  3. On the Roles page, click Create Role.

  4. In the Create Role panel, select Alibaba Cloud Account for the Select Trusted Entity parameter and click Next.

  5. Configure the RAM role.

    1. Specify RAM Role Name.

    2. Specify Note.

    3. Enter the ID of Account B in the Other Alibaba Cloud Account field.

      Note
  6. Click OK.

  7. Click Close.

  8. Use Account A to attach the AliyunFCReadOnlyAccess policy to the created RAM role. For more information about how to grant permissions to a RAM role, see Grant permissions to a RAM role.

After the RAM role is created, you can view the Alibaba Cloud Resource Name (ARN) and trust policy of the RAM role in the Basic Information section on the details page of the RAM role.

  • In this example, the ARN of the RAM role is acs:ram::123456789012****:role/fc-admin.

  • The following script shows the trust policy of the RAM role:

    Note

    This policy indicates that only RAM users that belong to Account B can assume the RAM role.

    {
      "Statement": [
        {
          "Action": "sts:AssumeRole",
          "Effect": "Allow",
          "Principal": {
            "RAM": [
              "acs:ram::134567890123****:root"
            ]
          }
        }
      ],
      "Version": "1"
    }

Step 2: Use Account B to create RAM users

  1. Use Account B to create RAM users for employees of enterprise B. For more information, see Create a RAM user.

  2. Use Account B to attach the AliyunSTSAssumeRoleAccess policy to the RAM users. Then, the RAM users can assume the RAM role. For more information about how to grant permissions to a RAM user, see Grant permissions to a RAM user.

Step 3: Switch the logon identity

If a RAM user that belongs to Account B needs to access resources of Account A, Account B can be used to grant the required permissions to the RAM user. The RAM user that belongs to Account B assumes the RAM role in Account A to access the resources of Account A. Perform the following operations:

  1. Use the RAM user that belongs to Account B to log on to the RAM console.

    For more information about how to log on to the console as a RAM user, see Log on to the Alibaba Cloud Management Console as a RAM user.

  2. Move the pointer over the profile picture in the upper-right corner of the console and click Switch Identity.

    1. Enter the enterprise alias (account alias), default domain name, or ID of the Alibaba Cloud account to which the RAM role belongs. For more information, see View and modify the default domain name.

    2. Enter the name of the RAM role. For more information, see View the information about a RAM role.

    For more information, see Assume a RAM role.

(Optional) Revoke the granted permissions

Enterprise A can revoke the permissions granted to Account B when the cooperation between Enterprise A and Enterprise B ends. Then, all RAM users that belong to Account B no longer have the permissions of the RAM role. Perform the following operations:

  1. Use Account A to log on to the RAM console.

  2. In the left-side navigation pane, choose Identities > Roles.

  3. On the Roles page, find the RAM role that you want to delete and click Delete in the Actions column.

  4. Click OK.

Note

Before you delete the RAM role, you must detach the policies that are attached to the RAM role. For more information, see Revoke permissions from a RAM role.

Use an SDK

You can use STS to authorize temporary access to Function Compute. STS is a web service that provides STS tokens for cloud computing users. The following example shows how Account B obtains the permissions to view all services in Account A.

Before you start

Create a function

Procedure

  1. Use Account A to create a RAM role and select Account B as the trusted account.

  2. Use Account B to create RAM users and authorize RAM users to assume the RAM role.

    For more information, see Create a RAM user and Grant permissions to a RAM user.

  3. In the function of Account B, enter the following sample code to obtain a temporary access credential. For more information, see STS SDK overview and AssumeRole.

    const Core = require('@alicloud/pop-core');
    
    // Build an Alibaba Cloud client that is used to initiate requests. 
    /*
        The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
        In this example, the AccessKey pair is stored in environment variables to implement identity verification. 
        Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables before you run the sample code. 
        The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
    */
     var client = new Core({
       accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
       accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
       endpoint: 'https://sts.aliyuncs.com',
       apiVersion: '2015-04-01'
     });
    
     // Configure the parameters. 
     var params = {
       "RegionId": "cn-hangzhou",
       "RoleArn": "<RoleARN>",
       "RoleSessionName": "<RoleSessionName>"
     }
    
     var requestOption = {
       method: 'POST'
     };
    
     // Initiate the request and obtain responses. 
     client.request('AssumeRole', params, requestOption).then((result) => {
       console.log(JSON.stringify(result));
     }, (ex) => {
       console.log(ex);
     })
    # -*- coding: utf-8 -*-
    from alibabacloud_tea_openapi.models import Config
    from alibabacloud_sts20150401.client import Client
    from alibabacloud_sts20150401.models import AssumeRoleRequest
    
    
    def main():
        # Enter the temporary key and temporary token.
        # The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        # We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
        In this example, the AccessKey pair is stored in environment variables to implement identity verification. 
        # Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your local environment before you run the sample code. 
        # In the runtime of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
        AccessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'))
        AccessKeyId=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
        regionId ='cn-hangzhou'
    
    
        config = Config(
            access_key_id='<ACCESS-KEY-ID>',
            access_key_secret='<ACCESS-KEY-SECRET>',
            region_id='cn-hangzhou'
        )
        client = Client(config)
    
        assume_role_request = AssumeRoleRequest(
            duration_seconds=3600,
            role_arn='<RoleARN>',
            role_session_name='fc-python-sdk'
        )
        response = client.assume_role(assume_role_request)
        response_json = json.loads(str(response.body).replace("'", "\"")) 
    	  result = json.dumps(response_json) 
    	  print(result)
    
    if __name__ == "__main__":
        main()

    The following sample code shows the expected output:

    {
      "RequestId": "964E0EC5-575B-4FF5-8FD0-D4BD8025602A",
      "AssumedRoleUser": {
        "Arn": "acs:ram::****:role/wss/wss",
        "AssumedRoleId": "***********:wss"
      },
      "Credentials": {
        "SecurityToken": "*************",
        "AccessKeyId": "STS.*************",
        "AccessKeySecret": "*************",
        "Expiration": "2023-05-28T11:23:19Z"
      }
    }
    Note

    For answers to frequently asked questions when you obtain the STS token, see FAQ about RAM roles and STS tokens.

  4. Modify the function code of Account B to authorize the RAM user that belongs to Account B to view all services in Function Compute within Account A.

    Sample code:

    const FC = require('@alicloud/fc2');
    // Build a client. 
    // Use the obtained temporary key. /*
        The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
        In this example, the AccessKey pair is stored in environment variables to implement identity verification. 
        Configure the ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN environment variables in your local environment before you run the sample code. 
        The ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN environment variables are automatically configured after you configure the execution permissions in the runtime of Function Compute. 
    */
    const client = new FC('<accountID>', {
        region: '<yourRegionID>',
        accessKeyID: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
        securityToken: process.env['ALIBABA_CLOUD_SECURITY_TOKEN'],
        accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
    });
    // Query services. 
    client.listServices().then(res => {
        console.log(JSON.stringify(res, null, ' '))
    }).catch(ex=> console.log(ex))
    Important

    Make sure that the role that is created by Account A and for which you want to grant the permissions of temporary key has the permission to query services.