All Products
Search
Document Center

Elastic Compute Service:Instance RAM roles

Last Updated:Nov 14, 2024

In Elastic Compute Service (ECS), an instance Resource Access Management (RAM) role is a regular service role that is attached to ECS instances, and the trusted entity of an instance RAM role is ECS. You can use an instance RAM role to obtain Security Token Service (STS) tokens as temporary access credentials from within an ECS instance without the need to provide an AccessKey pair. Then, you can use the temporary access credentials to call the API operations of other Alibaba Cloud services. You can obtain temporary access credentials only from within an ECS instance and do not need to provide an AccessKey pair. This ensures the security of the AccessKey pair of your Alibaba Cloud account and allows you to implement fine-grained access control and permission management by using RAM.

Benefits

  • Secure and convenient API operation calls within ECS instances: When your project is deployed on an ECS instance, you can use the capabilities provided by ECS to obtain STS tokens as temporary access credentials to call API operations without the need to configure an AccessKey pair in the code. This reduces the risk of AccessKey pair leaks.

  • Simplified RAM identity switchover: If you use the AccessKey pair of a RAM identity as the access credential for a service, you must change the AccessKey pair in the configurations or code and restart the service when you change your RAM identity. If you use an instance RAM role to obtain STS tokens as temporary access credentials for a service, you need to only change the instance RAM role when you change your RAM identity. No additional configurations are required.

  • Fine-grained permission management: You can attach instance RAM roles that include specific policies to different ECS instances. This allows you to implement fine-grained access control based on your business requirements.

Limits

Take note of the following limits when you attach instance RAM roles to ECS instances:

  • The ECS instances to which you want to attach instance RAM roles must reside in virtual private clouds (VPCs).

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

Procedure

If you use an Alibaba Cloud account to perform the subsequent operations, you do not need to grant the account additional permissions to configure and use instance RAM roles. If you use a RAM user or a RAM role to perform the subsequent operations, grant the RAM user or RAM role the following permissions.

Sample permissions

Grant the following permissions:

  • Manage instance RAM roles: Permissions to create instance RAM roles and grant permissions to the RAM roles.

  • Attach or detach instance RAM roles: Permissions to go to the Instance Details page of an ECS instance and attach an instance RAM role to or detach an instance RAM role from the instance.

  • Transfer RAM roles to cloud services: Permissions to perform the ram:PassRole action.

{
    "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 an instance RAM role and attach the instance RAM role to an ECS instance

Use the consoles

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

    1. Create an instance 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 the Create a regular service role section of the "Create a RAM role for a trusted Alibaba Cloud service" topic.

      • Select Trusted Entity: Select Alibaba Cloud Service.

      • Role Type: Select Normal Service Role.

      • Select Trusted Service: Select Elastic Compute Service.

        image

        image

    2. Grant permissions to the instance RAM role.

      Attach system policies or custom policies that you created to the instance RAM role to grant the instance RAM role the permissions to access or manage specific resources. For example, you can attach the AliyunOSSReadOnlyAccess policy to grant the instance RAM role the permissions to read data from Object Storage Service (OSS).

      Note

      You can attach system policies or custom policies to the instance RAM role. If the system policies do not meet your business requirements, 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 an instance RAM role and grant permissions to the 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 for an instance RAM role

You can obtain temporary access credentials from within an ECS instance by accessing the metadata service. The validity of the temporary access credentials is ensured. For more information, see Obtain instance metadata.

Method 1: Use the Alibaba Cloud Credentials tool

The Alibaba Cloud Credentials tool encapsulates the logic of calling the ECS metadata service to obtain STS tokens as temporary access credentials and supports periodic updates of temporary access credentials.

The following section provides examples on how to use the Alibaba Cloud Credentials tool in SDK for Python and SDK for Java.

Python
  1. Install the Alibaba Cloud Credentials tool.

    pip install alibabacloud_credentials
  2. Configure the ECS instance to use the instance RAM role to obtain 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 instance RAM role. If you do not specify this parameter, the system automatically obtains the name of the instance RAM role. To reduce the number of requests, we recommend that you specify this parameter.
    	role_name='<RoleName>'
    )
    credentialsClient = CredClient(credentialConfig)
    

Java

  1. Add the dependencies of credentials.

    <!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>credentials-java</artifactId>
        <version>0.3.4</version>
    </dependency>
  2. Configure the ECS instance to use the instance RAM role to obtain 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 instance RAM role. If you do not specify this parameter, the system automatically obtains the name of the instance RAM role. To reduce the number of requests, we recommend that you specify this parameter.
            credentialConfig.setRoleName("<RoleName>");
            Client credentialClient = new Client(credentialConfig);
        }
    }

Method 2: Use shell commands

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

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 Obtain instance metadata.

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

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>

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

The following sample code provides a sample response.

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

  • Expiration: indicates the point in time at which the temporary access credentials expire.

    {
       "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

In this example, a Python application that is deployed on a Linux ECS instance calls API operations by using the instance RAM role attached to the instance to download 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 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 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 = 'http://oss-cn-beijing-internal.aliyuncs.com'  # Specify the endpoint of the OSS bucket. If an internal endpoint is used, make sure that the ECS instance and the OSS bucket reside in the same region. 
    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 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 the Action parameter to Detach and click Confirm.

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

References