All Products
Search
Document Center

Elastic Compute Service:Use instance RAM roles to control access to resources

Last Updated:Mar 25, 2024

An instance RAM role is a type of RAM role that Elastic Compute Service (ECS) instances can assume to take on specific permissions. ECS instances can use the temporary access credentials of instance RAM roles to access and securely communicate with specific Alibaba Cloud services, such as Object Storage Service (OSS) and ApsaraDB RDS. This topic describes how to create an instance RAM role and attach the role to an ECS instance. This topic also provides an example on how to use an instance RAM role.

Overview

Applications that are deployed on ECS instances use the AccessKey pairs of Alibaba Cloud accounts or RAM users to access the APIs of other Alibaba Cloud services such as OSS, Virtual Private Cloud (VPC), and ApsaraDB RDS. Specific users configure AccessKey pairs on ECS instances to facilitate management and accelerate calls. For example, the users write AccessKey pairs to configuration files. However, this practice may cause issues such as information leaks, increased maintenance complexity, and excessive permissions. Instance RAM roles are provided to resolve the preceding issues. For example, you can use Security Token Service (STS) temporary credentials in ECS instances to access other Alibaba Cloud services. Then, you attach roles that include different policies to ECS instances to grant different access permissions on various resources. This way, you can implement fine-grained access control.

ECS instances can assume instance RAM roles that have specific access permissions.

Limits

The following limits apply when you attach instance RAM roles to ECS instances:

  • The ECS instances must be deployed in virtual private clouds (VPCs).

  • An ECS instance can be assigned only one instance RAM role.

Configure an instance RAM role

Important

If you use a RAM user to perform the procedure that is described in this topic, you must make sure that the RAM user is granted the permissions to configure the instance RAM role. For more information, see Authorize a RAM user to manage an instance RAM role.

Create an instance RAM role and attach the role to an ECS instance

Note

Each ECS instance can be assigned only one instance RAM role.

Use the console

  1. Log on to the RAM console to create an instance RAM role and grant permissions to the role.

    1. Create a RAM role whose trusted entity is an Alibaba Cloud service.

      In the left-side navigation pane, choose Identities > Roles. On the page that appears, click Create Role. In the Create Role panel, set the following parameters to specific values and configure other parameters based on your business requirements. For more information about parameter settings, see Create a RAM role for a trusted Alibaba Cloud service.

      • Select Trusted Entity: Select Alibaba Cloud Service.

      • Role Type: Select Normal Service Role.

      • Select Trusted Service: Select Elastic Compute Service.

    2. Grant permissions to the instance RAM role.

      On the Roles page, find the created instance RAM role and click Grant Permission in the Actions column. For example, you can attach the AliyunOSSReadOnlyAccessOSS policy to the instance RAM role.

      Note

      You can attach a system policy on the System Policy subtab or a custom policy on the Custom Policy subtab. For more information about how to create a custom policy, see Create custom policies.

  2. Attach the instance RAM role to an ECS instance.

    1. Log on to the ECS console.

    2. In the left-side navigation pane, choose Instances & Images > Instances.

    3. In the top navigation bar, select the region and resource group to which the resource belongs. 地域

    4. Find the desired ECS instance and choose 图标 > Instance Settings > Attach/Detach RAM Role in the Actions column.

    5. In the Attach/Detach RAM Role dialog box, select the instance RAM role that you created from the RAM Role drop-down list and click OK.

Call API operations

  1. Create and configure an instance RAM role.

    1. Call the CreateRole operation to create an instance RAM role.

      Set the AssumeRolePolicyDocument parameter to the following policy:

      {
           "Statement": [
           {
               "Action": "sts:AssumeRole",
               "Effect": "Allow",
               "Principal": {
               "Service": [
               "ecs.aliyuncs.com"
               ]
               }
           }
           ],
           "Version": "1"
       }
    2. Optional. Call the CreatePolicy operation to create a policy.

      If you have a policy that can be attached to the instance RAM role, skip this step.

      Set the PolicyDocument parameter to the following policy:

      {
           "Statement": [
               {
               "Action": [
                   "oss:Get*",
                   "oss:List*"
               ],
               "Effect": "Allow",
               "Resource": "*"
               }
           ],
           "Version": "1"
       }
    3. Call the AttachPolicyToRole operation to attach the policy to the instance RAM role.

  2. Call the AttachInstanceRamRole operation to attach the instance RAM role to an ECS instance.

Detach or change an instance RAM role

Use the console

  1. Log on to the ECS console.

  2. In the left-side navigation pane, choose Instances & Images > Instances.

  3. In the top navigation bar, select the region and resource group to which the resource belongs. 地域

  4. Find the desired ECS instance and choose 图标 > Instance Settings > Attach/Detach RAM Role in the Actions column.

    • To detach the instance RAM role, set Action to Detach and click Confirm.

    • To change the instance RAM role, set Action to Attach, select a different role from the RAM Role drop-down list, and then click Confirm.

      image.png

Call API operations

  • To detach an instance RAM role from an ECS instance, call the DettachInstanceRamRole operation.

  • To change the instance RAM role that is attached to an ECS instance, call the following operations:

    1. Call the DettachInstanceRamRole operation to detach the instance RAM role from the instance.

    2. Call the AttachInstanceRamRole operation to attach a different instance RAM role to the instance.

Example: Use instance RAM roles to access other Alibaba Cloud services

In this example, a Python application that is deployed on a Linux ECS instance uses an instance RAM role to download a picture from OSS.

  1. Make preparations.

    1. Create an instance RAM role, attach the AliyunOSSReadOnlyAccessOSS policy to the instance RAM role, and then attach the instance RAM role to the ECS instance.

      For more information, see Create and attach an instance RAM role in the "Attach an instance RAM role to an ECS instance" topic.

    2. Create a bucket in the region where the ECS instance resides, and obtain the name and endpoint of the bucket.

      For more information, see Create a bucket.

  2. Connect to the ECS instance, and install the OSS SDK for Python and alibabacloud_credentials.

    Note

    In this example, a Linux instance is used. For more information about how to install the OSS SDK for Python for Windows ECS instances, see Installation.

    pip install alibabacloud_credentials
    pip install oss2
  3. Use the SDK for Python to access OSS based on temporary credentials, and download a picture.

    Sample code (Replace specific information based on your business requirements):

    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    class CredentialProviderWarpper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            access_key_id = self.client.get_access_key_id()
            access_key_secret = self.client.get_access_key_secret()
            security_token = self.client.get_security_token()
            return Credentials(access_key_id, access_key_secret, security_token)
    
    def download_image_using_instance_role(bucket_name, endpoint, object_key, local_file, role_name):
        config = Config(
            type='ecs_ram_role',      # Specify the type of the temporary access credentials. Set the value to ecs_ram_role. 
            role_name=role_name # Specify the name of the instance RAM role that is attached to the ECS instance.
        )
        cred = Client(config)
        credentials_provider = CredentialProviderWarpper(cred)
        auth = oss2.ProviderAuth(credentials_provider)
    
        # Initialize the OSS bucket.
        bucket = oss2.Bucket(auth, endpoint, bucket_name)
        # Download the picture.
        bucket.get_object_to_file(object_key, local_file)
        print("Image downloaded successfully")
    
    if __name__ == "__main__":
        # Define the global variable role_name.
        role_name = 'ECSRoleName'  # Specify the name of the instance RAM role.
        bucket_name = 'bucket-name'  # Specify the name of the OSS bucket.
        endpoint = 'http://oss-cn-hangzhou.aliyuncs.com'  # Specify the public endpoint of OSS.
        object_key = 'image.png'  # Specify the OSS path where the picture you want to download is stored.
        local_file = '/home/image.png'  # Specify the path where you want to store the downloaded picture on the ECS instance.
        download_image_using_instance_role(bucket_name, endpoint, object_key, local_file, role_name)
    

References

After you attach an instance RAM role to an ECS instance, you must obtain the temporary authorization token of the instance RAM role if you want to access other Alibaba Cloud resources by using the instance RAM role. For more information, see Obtain a temporary authorization token.