All Products
Search
Document Center

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

Last Updated:Jul 24, 2024

To access resources of other Alibaba Cloud services, Elastic Compute Service (ECS) instances or applications that are deployed on the instances must have the corresponding access credentials. Alibaba Cloud services use the access credentials to authenticate the identities and permissions of the ECS instances or the applications deployed on the instances. 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 automatically obtain and refresh temporary access credentials from within the instance to access the resources of other Alibaba Cloud services without exposing AccessKey pairs. This reduces the risk of AccessKey pair leaks and allows RAM role-based, fine-grained management of access permissions on resources to prevent excessive permissions from being granted. 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 information about RAM roles, see the What is a RAM role? section of the "RAM role overview" topic.

Benefits

You can obtain the following benefits when you use instance RAM roles to obtain temporary access credentials for authentication and access control:

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

  • Cross-service access and fine-grained permission 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 permission 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

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

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

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

Procedure

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

Create an instance RAM role and grant the instance RAM role the required permissions to access specific Alibaba Cloud services. For example, to allow the ECS instance to access Object Storage Service (OSS), you must grant the instance RAM role the permissions to read data from and write data to OSS.

Important

If you use a RAM user to perform the procedure that is described in this topic, make sure that the RAM user is granted the permissions to use and configure instance RAM roles. For more information, see Grant RAM users permissions to use ECS resources.

Sample policy

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

    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 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 and write data to OSS.

      Note

      You can attach system policies or custom policies to the instance RAM role. If 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 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.

Use an instance RAM role to obtain temporary access credentials

After applications deployed on an ECS instance obtain temporary access credentials to access other Alibaba Cloud services, the applications leverage the temporary access credentials to call API operations in a secure manner to access or manage data across Alibaba Cloud services. The temporary access credentials are automatically updated on a periodic basis.

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 STS tokens as temporary access credentials based on the instance RAM roles. The temporary access credentials are updated on a periodic basis.

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.

Python
  1. Install the Alibaba Cloud Credentials tool.

    sudo pip install alibabacloud_credentials
  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 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.
            credentialConfig.setRoleName("<RoleName>");
            Client credentialClient = new Client(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 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);
        }
    }

Method 2: Obtain temporary access credentials from within an ECS instance by using metadata

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 Obtain 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 Obtain 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>

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

The following code snippet shows a sample response.

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

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 an image from OSS.

  1. Complete the preparations.

    1. Create an instance RAM role, attach the AliyunOSSReadOnlyAccess policy to the instance RAM role, and then attach the instance RAM role to a 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 from the Buckets page. For more information, see Create a bucket.

      Important

      If you want to access OSS over the Internet, make sure that the ECS instance can access the Internet. To allow the ECS instance to access the Internet over IPv4, you can modify the public bandwidth configurations of the ECS instance or associate an elastic IP address (EIP) with the ECS instance. For more information, see Modify the public bandwidth configurations of an instance associated with an auto-assigned public IP address or the Associate one or more EIPs with an instance section of the "Associate or disassociate an EIP" topic.

      image

      image

    3. Upload images to the OSS bucket. For more information, see the Use the OSS console section of the "Simple upload" topic.

  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 3 operating system is used. By default, Python 3 is installed on Alibaba Cloud Linux 3. If you use an ECS instance that runs another Linux operating system, change the commands in this section based on the Python version. If you use an ECS instance that runs a Windows operating system, use the procedure described in Installation to install OSS SDK for Python.

    1. Update the pip, setuptools, and wheel tools.

      sudo pip3 install --upgrade pip setuptools wheel
    2. Install the Alibaba Cloud Credentials tool.

      sudo pip3 install alibabacloud_credentials  
    3. Install the python-devel package on which OSS SDK for Python depends.

      sudo yum install python3-devel 
    4. 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 an image.

    Compile Python code. Sample Python code (Replace variables with the 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 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.
        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)

References