All Products
Search
Document Center

Elastic Compute Service:Configure an instance RAM role for an ECS instance

最終更新日:Mar 11, 2024

Instance Resource Access Management (RAM) roles are 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 configure and 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 Object Storage Service (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. To resolve the preceding issues, instance RAM roles are provided. For example, you can use STS temporary credentials of instance RAM roles on ECS instances to access other Alibaba Cloud services.

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).

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

Create and attach an instance RAM role

Important

If you use a RAM user to perform the procedure that is described in this topic, 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.

Use the consoles

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

    1. Create an instance RAM role.

      In the left-side navigation pane, choose Identities > Roles. Click Create Role. In the Create Role panel, set the following parameters to specific values and configure other parameters as prompted based on your business requirements:

      • 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.

  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 ECS instance that you want to manage 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 Confirm.

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 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 consoles

  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 ECS instance that you want to manage 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.

Sample: Use RAM roles to access other Alibaba Cloud services

In this example, SDK for Python is used to download a picture in a specified OSS bucket located within the same region as the instance through the STS temporary credential.

  1. Prerequisites.

    1. Create a RAM role and configure an authorization policy (AliyunOSSReadOnlyAccessOSS), and attach the RAM role to the instance.

      For more information, see Create and attach an instance RAM role.

    2. The region where the ECS instance is located has already created a Bucket, and the name and endpoint of the Bucket have been obtained.

      For more information, see Create a bucket.

  2. Remote connect to the ECS instance, and install the OSS Python SDK and alibabacloud_credentials.

    Note

    If you instance is a Windows instance, see Installation in OSS SDK reference.

    pip install alibabacloud_credentials
    pip install oss2
  3. Using Python SDK to access OSS with temporary credentials, and download pictures.

    The example code is as follows (part of the information needs to be replaced according to the comments):

    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',      # # Access credential type. Fixed to ecs_ram_role.
            role_name=role_name    # Name of the instance RAM role granted to ECS
        )
        cred = Client(config)
        credentials_provider = CredentialProviderWarpper(cred)
        auth = oss2.ProviderAuth(credentials_provider)
    
        # Initialize the OSS Bucket object
        bucket = oss2.Bucket(auth, endpoint, bucket_name)
        # Download the image to the local file
        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'  # Replace with the instance RAM role name
        bucket_name = 'bucket-name'  # Replace with the Bucket name
        endpoint = 'http://oss-cn-hangzhou.aliyuncs.com'  # Replace with the OSS public endpoint
        object_key = 'image.png'  # Replace with the storage path of the image you want to download in OSS
        local_file = '/home/image.png'  #  Replace with the path where the image needs to be stored in ECS
        download_image_using_instance_role(bucket_name, endpoint, object_key, local_file, role_name)