All Products
Search
Document Center

Elastic Compute Service:Instance RAM role

Last Updated:Mar 18, 2025

An instance RAM role is a RAM role assigned to an ECS instance. It is a regular service role with an Elastic Compute Service (ECS) instance as its trusted entity. Instance RAM roles allow you to retrieve Security Token Service (STS) tokens as temporary access credentials within an ECS instance, eliminating the need for an AccessKey pair. These temporary credentials enable API calls to other Alibaba Cloud services, enhancing the security of your Alibaba Cloud account's AccessKey pair and supporting fine-grained access control and permission management through RAM.

Advantages

  • Secure and convenient in-instance API call solution: Eliminate the need to configure an AccessKey in your code when your project is on Alibaba Cloud ECS. Instead, leverage ECS capabilities to retrieve temporary STS tokens for API calls, reducing AccessKey exposure risks.

  • Simplified RAM identity switching process: Avoid modifying configurations or code and restarting services when changing the RAM identity for service calls by simply updating the instance RAM role attached to the ECS instance.

  • Fine-grained permission management: Assign specific authorization policies to RAM roles for different ECS instances to achieve detailed access control tailored to your business needs.

Limits

The following restrictions apply when attaching an instance RAM role to an ECS instance:

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

  • Only one instance RAM role can be attached to an ECS instance at a time.

Implementation process

If you are using an Alibaba Cloud account for the following operations, no additional permissions are required to configure and use instance RAM roles. If a RAM user or RAM role is performing the operations, grant the necessary permissions to the RAM user or RAM role as follows.

Sample Permissions

The permissions primarily include the following:

  • Manage RAM roles: Create RAM roles and assign permissions to them.

  • Attach or detach RAM roles: Navigate to the product page of the instance to attach or detach RAM roles.

  • Allow the role to be passed to cloud services: Grant the ram:PassRole permission to the cloud service receiving the role.

{
    "Version": "1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:Describe*",
                "ecs:List*",
                "ecs:AttachInstanceRamRole",
                "ecs:DetachInstanceRAMRole"
            ],
            "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "ram:Describe*",              
            "ram:List*",
            "ram:Get*",
            "ram:CreateRole", 
            "ram:CreatePolicy", 
            "ram:AttachPolicyToRole"
          ],
          "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "ram:PassRole",
            "Resource": "*"
        }
    ]
}

Create a RAM role and attach it to an ECS instance

Create and attach the role in the console

  1. Log on to the RAM console and create a RAM role with the necessary permissions.

    1. Create a RAM role with an Alibaba Cloud service as the trusted entity.

      Select Identity Management > Roles and click Create Role. Follow the on-screen instructions to finalize the creation of the role. Pay attention to the following parameters, though you may configure additional parameters as necessary. For more information, see Create a regular service role:

      • Type of trusted entity: Select Alibaba Cloud Service .

      • Name of trusted entity: Select Elastic Compute Service .image

    2. Assign permissions to the created RAM role.

      Grant system or custom policies to the RAM role for resource access or management. For instance, you can assign the system policy AliyunOSSReadOnlyAccess to the RAM role.

      Note

      If system policies do not meet your needs, create custom policies for the RAM role. For more information, see Create a custom policy.

  2. Attach the 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 you want to manage and choose icon > Instance Settings > Attach Or Detach RAM Role.

    5. In the dialog box, select the RAM role for the instance you created and click OK.

Create and attach the role by calling API operations

  1. Create a RAM role and assign permissions.

    1. Use the CreateRole operation to create a RAM role.

      Parameters in the trust policy (AssumeRolePolicyDocument):

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

      Skip this step if you already have a suitable policy for the RAM role.

      The PolicyDocument must be set as follows:

      {
           "Statement": [
               {
               "Action": [
                   "oss:Get*",
                   "oss:List*"
               ],
               "Effect": "Allow",
               "Resource": "*"
               }
           ],
           "Version": "1"
       }
    3. Grant permissions to the instance RAM role by calling the AttachPolicyToRole operation.

  2. Attach the RAM role to the ECS instance using the AttachInstanceRamRole operation.

Obtain temporary access credentials for an instance RAM role

Access the metadata service within an ECS instance to obtain temporary access credentials. For details on metadata, refer to Instance metadata.

Method 1: Obtain temporary access credentials by using the Credentials tool

The Credentials tool encapsulates the logic for calling the ECS metadata service to retrieve STS tokens as temporary access credentials and supports the periodic updating of these credentials.

Python
  1. Install the Credentials tool.

    Note

    The version of alibabacloud_credentials must be 0.3.6 or later.

    pip install alibabacloud_credentials
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

    from alibabacloud_credentials.client import Client as CredClient
    from alibabacloud_credentials.models import Config as CredConfig
    
    credentialConfig = CredConfig(
    	type='ecs_ram_role',
    	# Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, the value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
    	role_name='<RoleName>'
    )
    credentialsClient = CredClient(credentialConfig)
    

Java

  1. Add the credentials dependency.

    Note

    The version of credentials-java must be 0.3.10 or later.

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
       <groupId>com.aliyun</groupId>
       <artifactId>credentials-java</artifactId>
       <version>LATEST</version>
    </dependency>
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

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

Go

  1. Install the Credentials tool.

    Note

    The version of credentials-go must be 1.3.10 or later.

    • Use go get to download and install the tool.

      go get -u github.com/aliyun/credentials-go
    • If you manage dependencies with dep, execute the following command.

      dep ensure -add github.com/aliyun/credentials-go
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

    package main
    
    import (
    	"fmt"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    func _main(args []*string) {
    	credentialsConfig := new(credentials.Config).
    		SetType("ecs_ram_role").
    		// Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, the value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable.
    		SetRoleName("<RoleName>")
    	credentialClient, err := credentials.NewCredential(credentialsConfig)
    	if err != nil {
    		panic(_err)
    	}
    }

Node.js

  1. Install the Credentials tool.

    Note

    The version of credentials must be 2.3.1 or later.

    npm install @alicloud/credentials
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

    const Credential = require('@alicloud/credentials');
    
    const credentialsConfig = new Credential.Config({
      type: 'ecs_ram_role',
      // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, the value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable.
      roleName: '<RoleName>',
    });
    const cred = new Credential.default(credentialsConfig);   

.NET

  1. Install the Credentials tool.

    Note

    The version of credentials must be 1.4.2 or later.

    dotnet add package Aliyun.Credentials
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

    using Aliyun.Credentials.Models;
    
    namespace credentials_demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var config = new Config()
                {
                    Type = "ecs_ram_role",
                  	// Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, the value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable.
                    RoleName = "<RoleName>" 
                }
            }
        }
    }

PHP

  1. Install the Credentials tool.

    Note

    The version of credentials must be 1.2.0 or later.

    composer require alibabacloud/credentials
  2. Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.

    <?php
    
    use AlibabaCloud\Credentials\Credential;
    use AlibabaCloud\Credentials\Credential\Config;
    
    $credConfig = new Config([
        'type' => 'ecs_ram_role',
        // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, the value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable.
        'roleName' => '<RoleName>',
    ]);

Method 2: Obtain temporary access credentials by using shell commands

The metadata service provides an HTTP endpoint for obtaining temporary access credentials.

Security hardening mode

  • Linux instance

    # Obtain access credentials from 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 a temporary authorization token for the instance RAM role
    curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/meta-data/ram/security-credentials/<Instance RAM role name>
  • Windows instance (PowerShell)

    # Obtain access credentials from 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 a temporary authorization token 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/<Instance RAM role name>

<Validity period of the metadata server access credentials>: Before obtaining a temporary authorization token for the instance RAM role, retrieve access credentials from the metadata server and set their validity period to enhance security. After the validity period expires, you must re-obtain the access credentials to continue receiving the temporary authorization token for the instance RAM role.

Valid values range from 1 to 21600 seconds. For more details, see Instance metadata.

<Instance RAM role name>: Replace this placeholder with the actual name of the instance RAM role, such as EcsRamRole.

NAT mode

  • Linux instance

    curl http://100.100.100.200/latest/meta-data/ram/security-credentials/<Instance RAM role name>
  • 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/<Instance RAM role name>

    <Instance RAM role name> Replace this placeholder with the actual instance RAM role name, such as EcsRamRoleDocumentTesting.

Below is a sample response with the following parameters:

  • AccessKeyId, AccessKeySecret, and SecurityToken comprise a temporary access token.

  • Expiration: The validity period of the temporary authorization token.

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

Use an instance RAM role to call API operations

This example demonstrates how to call API operations using an instance RAM role. A Python application, deployed on a Linux ECS instance, utilizes the attached instance RAM role to retrieve files from an OSS bucket.

pip install oss2  
pip install alibabacloud_credentials
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 credential type. 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 image.
    bucket.get_object_to_file(object_key, local_file)
    print("Image downloaded successfully")


if __name__ == "__main__":
    # Define global variables.
    role_name = 'role_name'  # Specify the name of the instance RAM role.
    bucket_name = 'bucket_name'  # Specify the name of the OSS bucket.
    endpoint = 'oss-cn-beijing.aliyuncs.com'  # Specify the endpoint of the OSS bucket.
    object_key = 'testfolder/example.png'  # Specify the path in which the image that you want to download is stored in OSS. The path does not include the bucket name.
    local_file = '/localpath/to/image.png'  # Specify a name for the image and the path in which you want to store the image on the ECS instance.
    download_image_using_instance_role(bucket_name, endpoint, object_key, local_file, role_name)

Other operations

Detach or change the instance RAM role of an ECS instance

Detach or change the role in 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. Locate the ECS instance you want to manage and select icon > Instance Settings > Attach or Detach RAM Role.

    • To detach the instance RAM role, select Operation Type and then choose Detach. Click OK.

    • To change the instance RAM role, select Operation Type and then choose Attach. Pick the necessary instance RAM role and click OK to finalize the change.

      image.png

Detach or change the role by calling API operations

References