All Products
Search
Document Center

Elastic Compute Service:Grant ECS access to resources of other Alibaba Cloud services by using instance RAM roles

最終更新日:May 14, 2024

To access resources of other Alibaba Cloud services, Elastic Compute Service (ECS) instances or applications that are deployed on the instances must use access credentials to authenticate identities and permissions. You can attach an instance Resource Access Management (RAM) role to an ECS instance. The ECS instance and the applications that are deployed on the instance can use the Security Token Service (STS) tokens of the instance RAM role to access the resources of other Alibaba Cloud services without the need to provide AccessKey pairs. This reduces the risk of AccessKey pair leaks and allows RAM-based, fine-grained management of access permissions on resources, which prevents excessive permissions from being granted. STS tokens are temporary access credentials, whereas AccessKey pairs are long-term access credentials. This topic describes how to create an instance RAM role, attach the instance RAM role to an ECS instance, and obtain temporary access credentials based on the instance RAM role.

Note

An instance RAM role is a type of RAM role whose trusted entity is an Alibaba Cloud service. This type of RAM role is used to grant access across Alibaba Cloud services and can be assumed by Alibaba Cloud services. For more information, see RAM role overview.

Benefits

Using instance RAM roles to obtain temporary access credentials for authentication and access control provides the following benefits:

  • Enhanced communication security: You can use STS tokens instead of AccessKey pairs to access resources, which reduces the risk of AccessKey pair leaks.

  • Across-service access and fine-grained permissions management: You can attach instance RAM roles that include different policies to grant ECS instances access only to specific resources based on the principle of least privilege.

  • Simplified permissions maintenance: You can modify the policies of instance RAM roles that are attached to ECS instances to modify and manage the access permissions of the instances without the need to manage credentials on the instances.

Limits

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

  • You must deploy the ECS instances in virtual private clouds (VPCs).

  • You can assign only one instance RAM role to an ECS instance.

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

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 Use RAM to manage ECS permissions.

Custom policies

[ECS RAM Action] indicates the permissions that can be granted to the RAM user.

{
    "Version": "1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs: [ECS RAM Action]",
                "ecs: CreateInstance",
                "ecs: AttachInstanceRamRole",
                "ecs: DetachInstanceRAMRole"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "ram:PassRole",
            "Resource": "*"
        }
    ]
}

Use the consoles

  1. Log on to the RAM console to create an instance RAM role and grant permissions to the instance RAM 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 Roles page, click Create Role. On the Create Role page, set the following parameters to specific values and configure other parameters based on your business requirements. For information about the 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 grant the instance RAM role access to Object Storage Service (OSS).

      Note

      You can attach system policies or custom policies to the instance RAM role. You can create custom policies. For more information, 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 ECS instance to which you want to attach the instance RAM role 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 already 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.

Obtain temporary access credentials based on an instance RAM role

Method 1: Use the Alibaba Cloud Credentials tool in an SDK

The Alibaba Cloud Credentials tool obtains the instance RAM roles that are attached to ECS instances and then calls the metadata service (metadata server) of ECS to obtain temporary access credentials based on the instance RAM roles. The temporary access credentials are updated on a periodic basis.

Important

Before you can use the Alibaba Cloud Credentials tool to obtain temporary access credentials based on instance RAM roles, you must install the tool.

sudo pip install alibabacloud_credentials

The following sample code provides examples on how to use the Alibaba Cloud Credentials tool in SDK for Python and SDK for Java. To view the sample code for SDKs in other programming languages, see the Sample code section of the "Best practices for using an access credential to call API operations" topic.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='ecs_ram_role',
	# Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
	role_name='<RoleName>'
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class DemoTest {
    public static void main(String[] args) throws Exception {
        Config config = new Config();
        config.setType("ecs_ram_role");
        // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
        config.setRoleName("<RoleName>");
        Client client = new Client(config);
    }
}

Method 2: Access the metadata server

In specific scenarios, if you do not have or cannot use the Alibaba Cloud Credentials tool or you want to obtain temporary access credentials based on instance RAM roles in a script, you can access the metadata server from within ECS instances.

Note

You can access the metadata server to obtain instance metadata from within ECS instances without the need to log on to the ECS console or call API operations. For more information, see Access instance metadata.

Security hardening mode

  • Linux instance

    # Obtain the access credentials of the metadata server for authentication.
    TOKEN=`curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds:<Validity period of the metadata server access credentials>"` 
    # Obtain temporary access credentials for the instance RAM role.
    curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/meta-data/ram/security-credentials/<Name of the instance RAM role>
  • Windows instance (PowerShell)

    # Obtain the access credentials of the metadata server for authentication.
    $token = Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "<Validity period of the metadata server access credentials>"} -Method PUT –Uri http://100.100.100.200/latest/api/token
    # Obtain temporary access credentials for the instance RAM role.
    Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token" = $token} -Method GET -Uri http://100.100.100.200/latest/meta-data/ram/security-credentials/<Name of the instance RAM role>

<Validity period of the metadata server access credentials>: Before you can obtain temporary access credentials for the instance RAM role, you must obtain the access credentials of the metadata server and specify a validity period for the credentials to increase data security. After the specified validity period ends, you must re-obtain the access credentials of the metadata server. Otherwise, you cannot obtain temporary access credentials for the instance RAM role.

Valid values: 1 to 21600. Unit: seconds. For more information, see Access instance metadata.

<Name of the instance RAM role>: Replace <Name of the instance RAM role> with an actual value. Example: EcsRamRoleDocumentTesting.

Normal mode

  • Linux instance

    curl http://100.100.100.200/latest/meta-data/ram/security-credentials/<Name of the instance RAM role>
  • Windows instance (PowerShell)

    Invoke-RestMethod http://100.100.100.200/latest/meta-data/Invoke-RestMethod http://100.100.100.200/latest/meta-data/ram/security-credentials/<Name of the instance RAM role>

    <Name of the instance RAM role>: Replace <Name of the instance RAM role> with an actual value. Example: EcsRamRoleDocumentTesting.

The following code snippet shows a sample response, in which:

  • SecurityToken: indicates the temporary access credentials of the instance RAM role.

  • Expiration: indicates the time when the temporary access credentials of the instance RAM role expire.

    {
       "AccessKeyId" : "STS.*******6YSE",
       "AccessKeySecret" : "aj******jDU",
       "Expiration" : "2017-11-01T05:20:01Z", 
       "SecurityToken" : "CAISng********",
       "LastUpdated" : "2023-07-18T14:17:28Z",
       "Code" : "Success"
    }

Detach or change an instance RAM role

Use the ECS 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 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 that is attached to the ECS instance, set Action to Detach and click Confirm.

    • To change the instance RAM role that is attached to the ECS instance, set Action to Attach, select a different instance RAM 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 ECS instance.

    2. Call the AttachInstanceRamRole operation to attach a different instance RAM role to the ECS 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 Linux ECS instance.

      For more information, see the Create an instance RAM role and attach the instance RAM role to an ECS instance section of this topic.

    2. Create an OSS 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 Linux ECS instance and install OSS SDK for Python and the Alibaba Cloud Credentials tool.

    Note

    In this example, an ECS instance that runs an Alibaba Cloud Linux operating system is used. For information about how to install OSS SDK for Python on other operating systems, see Installation.

    # Update pip3, setuptools, and wheel.
    sudo pip3 install --upgrade pip setuptools wheel
    # Install the Alibaba Cloud Credentials tool.
    sudo pip3 install alibabacloud_credentials  
    # Install the python-devel package on which OSS SDK for Python depends.
    sudo yum install python3-devel
    # Install OSS SDK for Python.
    sudo pip3 install oss2 
  3. Use the temporary access credentials of the instance RAM role to access OSS, and download a picture.

    Sample Python code (Replace specific information with actual values):

    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 access credential. Set this parameter to ecs_ram_role. 
            role_name=role_name
        )
        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 global variables.
        role_name = 'oss-test'  # Specify the name of the instance RAM role.
        bucket_name = 'ecs-ram'  # Specify the name of the bucket.
        endpoint = 'http://oss-cn-hangzhou.aliyuncs.com'  # Specify the public endpoint of the bucket.
        object_key = 'testfolder/example.png'  # Specify the path in which the picture you want to download is stored in OSS. The path does not include the bucket name.
        local_file = '/home/image.png'  # Specify a name for the picture and the path in which you want to store the picture on the ECS instance.
        download_image_using_instance_role(bucket_name, endpoint, object_key, local_file, role_name)

References