All Products
Search
Document Center

Elastic Compute Service:Instance RAM roles

Last Updated:Dec 25, 2025

An instance Resource Access Management (RAM) role is a service role that you can attach to an Elastic Compute Service (ECS) instance. The trusted entity of an instance RAM role is ECS. You can use an instance RAM role to obtain a Security Token Service (STS) token from within an ECS instance without providing an AccessKey pair. You can then use the STS token to call the API operations of other Alibaba Cloud services. You can obtain the temporary identity credential only from within an instance. This eliminates the need to configure an AccessKey pair, which enhances the security of your Alibaba Cloud account's AccessKey pair and lets you implement fine-grained permission management using RAM.

Benefits

  • Secure and convenient API calls within instances: When your project is deployed on Alibaba Cloud ECS, you can use an instance RAM role to obtain an STS token to call APIs instead of configuring an AccessKey pair in your code. This reduces the risk of AccessKey pair leaks.

  • Simplified RAM identity switching: If you use a traditional AccessKey pair, you must modify the configuration or code and restart the service to change the RAM identity that calls the service. If you use an instance RAM role, you only need to change the RAM role that is attached to the ECS instance to switch identities. No other changes are required.

  • Fine-grained permission management: You can assign RAM roles with specific authorization policies to different ECS instances. This lets you implement fine-grained access control as needed.

Limits

You can attach only one RAM role to an ECS instance.

Procedure

If you use a RAM user or RAM role to perform the following operations, grant the required permissions to that identity.

Sample permissions

This permission includes the following:

  • Manage RAM roles: Create RAM roles and grant permissions.

  • Attach or detach RAM roles: Allows you to attach a RAM role to or detach a RAM role from an instance.

  • Allow passing roles to Alibaba Cloud services: The ram:PassRole permission is required to grant a role to an Alibaba Cloud service.

{
    "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 a role in the console

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

    1. Create a RAM role for a trusted Alibaba Cloud service.

      Choose Identities > Roles, click Create Role, and follow the on-screen instructions to create the role. Note the following parameters and configure other parameters as needed. For more information, see Create a service role:

      • For Trusted Entity Type, select Alibaba Cloud Service.

      • For Trusted Service, select Elastic Compute Service.

    2. Grant permissions to the created RAM role.

      Attach a system policy or a custom policy to the RAM role to grant it the required resource access or operation permissions. For example, grant the AliyunOSSReadOnlyAccess system policy to the RAM role.

      If the system policies do not meet your requirements, you can grant permissions to a RAM role by creating a custom policy. For more information, see Create a custom policy.
  2. Attach the RAM role to an ECS instance.

    1. Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.

    2. Find the target ECS instance and choose 图标 > Instance Settings > Attach/Detach RAM Role.

    3. In the dialog box, select the instance RAM role and click OK.

Creation via API and granting

  1. Create a RAM role and grant permissions.

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

      Parameter for the trust policy (AssumeRolePolicyDocument):

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

      If you have an available access policy, you can skip this step.

      Set the PolicyDocument parameter as follows:

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

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

Obtain temporary identity credentials for an instance RAM role

You can obtain temporary access credentials from within an ECS instance by accessing the Instance Metadata Service (IMDS). The validity period of the temporary access credentials is automatically managed. For more information about metadata, see Instance metadata.

Method 1: Use the Credentials tool in a program

The Credentials tool encapsulates the logic of calling the ECS IMDS to obtain an STS token. It also supports periodic renewal.

Python
  1. Install the Credentials tool.

    To retrieve temporary identity credentials in security hardening mode, the version of alibabacloud_credentials must be 0.3.6 or later.
    pip install alibabacloud_credentials
  2. Configure the RAM role of the ECS instance as the access credential.

    from alibabacloud_credentials.client import Client as CredClient
    from alibabacloud_credentials.models import Config as CredConfig
    
    credentialsConfig = CredConfig(
    	type='ecs_ram_role',
    	# Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
    	role_name='<role_name>',
    	# Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
    	disable_imds_v1=False,
    )
    credentialsClient = CredClient(credentialsConfig)
    

    For more information and invocation examples, see Method 5: ECS instance RAM role.

Java

  1. Add the credentials dependency.

    To retrieve temporary identity credentials in security hardening mode, 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>0.3.10</version>
    </dependency>
  2. You can configure the ECS instance to use its instance RAM role as the access credential.

    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. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
            credentialConfig.setRoleName("<RoleName>");
            // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
            credentialConfig.setDisableIMDSv1(true);
            Client credentialClient = new Client(credentialConfig);
        }
    }

    For more information and invocation examples, see Method 5: ECS instance RAM role.

Go

  1. Install the Credentials tool.

    To retrieve temporary identity credentials in security hardening mode, 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 use dep to manage dependencies, run the following command.

      dep ensure -add github.com/aliyun/credentials-go
  2. Configure the instance RAM role of the ECS instance as the access credential.

    package main
    
    import (
    	"fmt"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    func _main(args []*string) {
    	credentialsConfig := new(credentials.Config).
    		SetType("ecs_ram_role").
    		// Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
    		SetRoleName("<RoleName>").
    		// Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
    		SetDisableIMDSv1(true)
    	credentialClient, err := credentials.NewCredential(credentialsConfig)
    	if err != nil {
    		panic(err)
    	}
    }

    For more information and invocation examples, see Method 5: Use an ECS instance RAM role.

Node.js

  1. Install the Credentials tool.

    To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 2.3.1 or later.
    npm install @alicloud/credentials
  2. Configure the instance RAM role of the ECS instance as the access credential.

    const Credential = require('@alicloud/credentials');
    
    const credentialsConfig = new Credential.Config({
      type: 'ecs_ram_role',
      // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
      roleName: '<RoleName>',
      // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
      disableIMDSv1: true,
    });
    const cred = new Credential.default(credentialsConfig);
    

    For more information and invocation examples, see Method 5: Use an ECS instance RAM role.

.NET

  1. Install the Credentials tool.

    To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 1.4.2 or later.
    dotnet add package Aliyun.Credentials
  2. Configure the instance RAM role of the ECS instance as the access credential.

    using Aliyun.Credentials.Models;
    
    namespace credentials_demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var config = new Config()
                {
                    Type = "ecs_ram_role",
                  	// Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
                    RoleName = "<RoleName>",
                    // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
                    DisableIMDSv1 = true
                }
            }
        }
    }

    For more information and invocation examples, see Method 5: Use an ECS instance RAM role.

PHP

  1. Install the Credentials tool.

    To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 1.2.0 or later.
    composer require alibabacloud/credentials
  2. Configure the ECS instance to use its instance RAM role as the access credential.

    <?php
    
    use AlibabaCloud\Credentials\Credential;
    use AlibabaCloud\Credentials\Credential\Config;
    
    $credConfig = new Config([
        'type' => 'ecs_ram_role',
        // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable.
        'roleName' => '<RoleName>',
        // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1).
        'disableIMDSv1' => true,
    ]);

    For more information, see Method 5: Use an ECS instance RAM role.

Method 2: Use shell commands

The metadata service provides an HTTP endpoint to retrieve temporary access credentials.

Security hardening mode

  • Linux instance

    # Obtain the access token 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_token>"` 
    # Obtain the temporary access credentials of 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 the access token of the metadata server for authentication.
    $token = Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "<validity_period_of_the_metadata_server_access_token>"} -Method PUT -Uri http://100.100.100.200/latest/api/token
    # Obtain the temporary access credentials of 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_token>: Before you retrieve the temporary access credentials of the instance RAM role, you must first obtain an access token for the metadata server. This token has a configurable validity period to enhance data security. After the token expires, you must obtain a new one before you can retrieve the temporary access credentials.

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

<instance_RAM_role_name>: Replace this with the name of your instance RAM role. For example, EcsRamRole.

Note

If you use Cloud Assistant to run the preceding commands, make sure that the Cloud Assistant Agent meets the following minimum version requirements:

Platform

Cloud Assistant Agent version number

windows

2.1.3.857

linux

2.2.3.857

linux arm

2.4.3.857

freebsd

2.3.3.857

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/ram/security-credentials/<instance_RAM_role_name>

    Replace <instance_RAM_role_name> with the name of your instance RAM role. For example, EcsRamRoleDocumentTesting.

The following is a sample response:

  • The temporary access credentials consist of the AccessKeyId, AccessKeySecret, and SecurityToken values.

  • Expiration: The expiration time of the temporary access credentials.

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

Method 3: Use the Alibaba Cloud CLI

The command-line interface (CLI) supports calling the ECS IMDS to obtain an STS token. It also supports periodic and automatic refreshes.

To retrieve temporary identity credentials in security hardening mode, the version of the CLI must be 3.0.248 or later.
  1. Install the CLI.

  2. Configure identity credentials.

    Run the following command to configure credential information. Replace <ProfileName> with the name of your configuration.

    aliyun configure --profile <ProfileName> --mode EcsRamRole

    This is an interactive command. Follow the prompts to enter the required information. For more information, see Configure credentials.

  3. Call an API operation.

    For example, use the CLI to query the list of ECS instances.

     aliyun ecs DescribeInstances

    For more information about CLI commands, see Command structure.

Use an instance RAM role to call an API

The following example shows how to use an instance RAM role. A Python application deployed on a Linux ECS instance calls an OSS API operation to download a file.

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',      # The type of access credential. This value is fixed as ecs_ram_role.
        role_name=role_name
    )
    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 instance.
    bucket.get_object_to_file(object_key, local_file)
    print("Image downloaded successfully")


if __name__ == "__main__":
    # Define global variables.
    role_name = 'role_name'  # Replace with the name of your instance RAM role.
    bucket_name = 'bucket_name'  # Replace with your bucket name.
    endpoint = 'oss-cn-beijing.aliyuncs.com'  # Replace with the public endpoint of your OSS bucket.
    object_key = 'testfolder/example.png'  # Replace with the full path of the image that you want to download from OSS. Do not include the bucket name.
    local_file = '/localpath/to/image.png'  # Replace with the root path on the ECS instance where you want to store the image, and define the image name.
    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 a role in the console

  1. Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.

  2. Find the ECS instance that you want to manage, and choose icon > Instance Settings > Attach/Detach RAM Role.

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

    • To change the instance RAM role, set Operation Type to Attach, select the required instance RAM role, and then click OK.

Detach or change a role using the API

References