All Products
Search
Document Center

Elastic Compute Service:Instance RAM roles

Last Updated:Apr 27, 2026

Attach an instance RAM role to an ECS instance to obtain STS tokens for calling other Alibaba Cloud APIs without exposing an AccessKey pair.

Benefits

  • Secure API calls: Obtain STS tokens from ECS without embedding an AccessKey pair in your code, reducing the risk of credential leaks.

  • Simplified identity switching: Switch the RAM identity by changing the instance RAM role instead of modifying code or restarting the service.

  • Fine-grained access control: Assign RAM roles with specific policies to different ECS instances for granular permission management.

Limitations

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

Procedure

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

Sample permissions

The policy must include these permissions:

  • Manage RAM roles: Create RAM roles and attach policies.

  • Attach or detach RAM roles: Attach or detach a RAM role on the instance details page.

  • Pass roles to 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

Console

  1. Log on to the RAM console to create a RAM role and attach policies.

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

      Select Identities > Roles, click Create Role, and follow the on-screen instructions. Note the following parameters. See Create a RAM role for a trusted Alibaba Cloud service:

      • Principal Type: Select Cloud Service.

      • Principal Name, select ECS.

    2. Grant permissions to the created RAM role.

      Attach a system policy or a custom policy to the RAM role. For example, attach the AliyunOSSReadOnlyAccess system policy.

      To create custom policies, see Create a custom policy.
  2. Attach the RAM role to an ECS instance.

    1. Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target resource.

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

    3. In the dialog box, select the instance RAM role that you created, and then click OK.

API

  1. Create a RAM role and attach policies.

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

      Set AssumeRolePolicyDocument to the following trust policy:

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

      Skip this step if you already have a suitable access policy.

      Set PolicyDocument as follows:

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

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

Obtain temporary credentials

Obtain temporary credentials from within an ECS instance by accessing the metadata service. Credential validity is managed automatically. See Instance metadata.

Use the Credentials tool

The Credentials tool wraps the ECS IMDS to obtain and periodically refresh STS tokens.

Python
  1. Install the Credentials tool.

    Security hardening mode requires alibabacloud_credentials 0.3.6 or later.
    pip install alibabacloud_credentials
  2. Configure the ECS instance RAM role 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 normal mode (IMDSv1).
    	disable_imds_v1=False,
    )
    credentialsClient = CredClient(credentialsConfig)
    

    See Method 5: ECS Instance RAM Role.

Java

  1. Add the credentials dependency.

    Security hardening mode requires credentials-java 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. Configure the ECS 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 normal mode (IMDSv1).
            credentialConfig.setDisableIMDSv1(true);
            Client credentialClient = new Client(credentialConfig);
        }
    }

    See Method 5: ECS instance RAM role.

Go

  1. Install the Credentials tool.

    Security hardening mode requires credentials-go 1.3.10 or later.
    • Use go get to install:

      go get -u github.com/aliyun/credentials-go
    • If you use dep to manage dependencies:

      dep ensure -add github.com/aliyun/credentials-go
  2. Configure the ECS instance RAM role 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 normal mode (IMDSv1).
    		SetDisableIMDSv1(true)
    	credentialClient, err := credentials.NewCredential(credentialsConfig)
    	if err != nil {
    		panic(err)
    	}
    }

    See Method 5: Using ECS instance RAM roles.

Node.js

  1. Install the Credentials tool.

    Security hardening mode requires credentials 2.3.1 or later.
    npm install @alicloud/credentials
  2. Configure the ECS instance RAM role 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 normal mode (IMDSv1).
      disableIMDSv1: true,
    });
    const cred = new Credential.default(credentialsConfig);
    

    See Method 5: Using an ECS instance RAM role.

.NET

  1. Install the Credentials tool.

    Security hardening mode requires credentials 1.4.2 or later.
    dotnet add package Aliyun.Credentials
  2. Configure the ECS instance RAM role 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 normal mode (IMDSv1).
                    DisableIMDSv1 = true
                }
            }
        }
    }

    See Method 5: Use an ECS instance RAM role.

PHP

  1. Install the Credentials tool.

    Security hardening mode requires credentials 1.2.0 or later.
    composer require alibabacloud/credentials
  2. Configure the ECS 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 normal mode (IMDSv1).
        'disableIMDSv1' => true,
    ]);

    See Method 5: Use an ECS instance RAM role.

Use shell commands

Retrieve temporary credentials through the metadata service HTTP endpoint.

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>: The validity period of the metadata server access token. The token must be obtained before retrieving temporary credentials. After expiration, obtain a new token.

Valid values: 1 to 21600. Unit: seconds. 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 these commands, the Cloud Assistant Agent must meet the following minimum version requirements:

Platform

Minimum Cloud Assistant Agent version

windows

2.1.3.857

linux

2.2.3.857

linux arm

2.4.3.857

freebsd

2.3.3.857

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

Sample response:

  • The temporary access token consists of AccessKeyId, AccessKeySecret, and SecurityToken.

  • Expiration: The expiration time of the temporary credentials.

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

Use the CLI

The CLI wraps the ECS IMDS to obtain and automatically refresh STS tokens.

Security hardening mode requires CLI 3.0.248 or later.
  1. Install the CLI.

  2. Configure identity credentials.

    Configure credential information. Replace <ProfileName> with the name of your configuration.

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

    Follow the prompts to enter the required information. See Configure credentials.

  3. Call an API operation.

    For example, query the list of ECS instances:

     aliyun ecs DescribeInstances

    See Command structure.

Example: Call an API with an instance RAM role

The following Python example downloads a file from OSS using an instance RAM role on a Linux ECS instance.

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 an instance RAM role

Console

  1. Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target resource.

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

    • To detach an instance RAM role: Set Action to Detach and click Confirm.

    • To change the instance RAM role: Set Action to Attach, select the desired instance RAM role, and then click Confirm.

API

References