All Products
Search
Document Center

:Use RAM roles to access other Alibaba Cloud services

Last Updated:Mar 14, 2024

This topic describes how to use Resource Access Management (RAM) roles to enable applications that are deployed on Elastic Compute Service (ECS) instances to access other Alibaba Cloud services by using Security Token Service (STS) temporary credentials. In this topic, Python is used to access Object Storage Service (OSS) as an example.

Prerequisites

An ECS instance is created. For information about how to create an instance, see Create an instance on the Custom Launch tab.

Background information

Compared with the traditional access method of using AccessKeyIDs and AccessKeySecrets (AKs), using RAM roles to access other Alibaba Cloud services is more convenient and does not require special management. This topic describes how to use RAM roles to access other Alibaba Cloud services.

  • AK method: Previously, applications deployed on an ECS instance needed to use AKs to access other Alibaba Cloud services. An AK allows you to access Alibaba Cloud APIs with full permissions for your account. To facilitate the management of the AK by applications, you must store the AK in the application configuration files or on an ECS instance. However, this increases the complexity of AK management and reduces the confidentiality of the AK. If you want to achieve consistent deployment across regions, the AK is spread along with the images or instances created from the images. In this case, you must update and redeploy each instance and image every time you make changes to the AK.

  • RAM role method: You can attach a RAM role to an ECS instance, and use an STS temporary credential to access other cloud services from the applications that are deployed on the instance. STS temporary credentials are generated and updated automatically. Applications can obtain the STS temporary credentials by using the instance metadata URL. You can use RAM roles and authorization policies to grant ECS instances different or identical permissions to access other cloud services.

Important

To help you get started with the examples, all operations in this topic are performed in OpenAPI Explorer. OpenAPI Explorer obtains a temporary AK of the current account through the information of the logged user, and performs online resource operations on the current account. You are charged for creating an instance. Release the instance after the operations are complete.

Procedure

To use a RAM role to enable Python that is deployed on an ECS instance to access OSS by using an STS temporary credential, perform the following steps:

Step 1: Create a RAM role and attach a policy to the RAM role

  1. Create a RAM role.

    Call the CreateRole operation to create a RAM role. The relevant parameters are:

    • RoleName: Set the name of the RAM role. Set the parameter based on your business requirements. EcsRamRoleTest is used in this example.

    • AssumeRolePolicyDocument: Configure a policy that allows one or more trusted entities to assume the RAM role. The trusted entities can be Alibaba Cloud accounts, Alibaba Cloud services, or identity providers (IdPs). In this example, the following sample code is used to specify that the trusted entity allowed to assume the RAM role is an ECS cloud service in the current Alibaba Cloud account:

      {
          "Statement": [
              {
                  "Action": "sts:AssumeRole", 
                  "Effect": "Allow", 
                  "Principal": {
                      "Service": [
                          "ecs.aliyuncs.com"
                      ]
                  }
              }
          ], 
          "Version": "1"
      }

  2. Create an authorization policy.

    Call the CreatePolicy operation to create an authorization policy. Specify the following parameters:

    • PolicyName: Set the name of the authorization policy. Example: EcsRamRolePolicyTest.

    • PolicyDocument: Enter the content of the authorization policy. In this example, the following content is used to specify that the RAM role has the OSS read-only permission.

      {
          "Statement": [
              {
                  "Action": [
                      "oss:Get*", 
                      "oss:List*"
                  ], 
                  "Effect": "Allow", 
                  "Resource": "*"
              }
          ], 
          "Version": "1"
      }

  3. Grant permissions to the RAM role.

    Call the AttachPolicyToRole operation to grant permissions to the role. Specify the following parameters:

    • PolicyType: Set the parameter to Custom.

    • PolicyName: Set the parameter to the name of the authorization policy created in Step 2. Example: EcsRamRolePolicyTest.

    • RoleName: Set the parameter to the name of the role created in Step 1. Example: EcsRamRoleTest.

Step 2: Create an ECS instance and attach the RAM role to the instance

You can use one of the following methods to create an ECS instance and attach the RAM role to the instance:

  • Attach the RAM role to an existing ECS instance

    Call the AttachInstanceRamRole operation to attach the RAM role to an existing instance of the Virtual Private Cloud (VPC) network type.

    • RegionId: Enter the region ID of the ECS instance.

    • RamRoleName: Enter the name of the RAM role. EcsRamRoleTest is used in this example.

    • InstanceIds: Enter the IDs of the instances of the VPC network type to which you want to attach the RAM role. ["i-bXXXXXXXX"] is used in this example.

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

    1. Create an ECS instance.

      Call the CreateInstance operation to create an ECS instance. Configure the parameters based on your business requirements. The following parameters are required:

      • RegionId: the region ID of the ECS instance. Example: cn-hangzhou.

      • ImageId: the ID of the image file. Example: centos_7_03_64_40G_alibase_20170503.vhd.

      • InstanceType: the instance type of the instance. Example: ecs.g6.large.

      • VSwitchId: the ID of the vSwitch in the VPC to which the instance belongs. RAM roles can be attached to only instances of the VPC network type. In this case, the VSwitchId parameter is required.

      • RamRoleName: the name of the RAM role. Example: EcsRamRoleTest.

      (Optional) If you want to authorize a RAM user to create an ECS instance with the specified RAM role attached, the RAM user must have the permission to create an ECS instance and the PassRole permission. In this case, you must create a custom authorization policy and attach the policy to the RAM user. The following sample code provides an example on how to create a custom authorization policy:

      {
          "Statement": [
              {
                  "Action": "[ECS RAM Action]", 
                  "Resource": "*", 
                  "Effect": "Allow"
              }, 
              {
                  "Action": "ram:PassRole", 
                  "Resource": "*", 
                  "Effect": "Allow"
              }
          ], 
          "Version": "1"
      }
      • If you want to configure the RAM user to create an ECS instance, replace the value of [ECS RAM Action] with ecs:CreateInstance. You can grant more permissions to the RAM user based on your business requirements.

      • If you want to grant all ECS permissions to the RAM user, you must replace the value of [ECS RAM Action] with ecs:*.

      Note

      For information about the values of [ECS RAM Action], see Authorization rules.

    2. Configure the password and start the instance.

      For more information, see Reset the logon password of an instance from within the instance and Start an instance.

    3. Configure the instance to access the Internet in the ECS console or by calling an API operation.

      In this example, an API operation is called to assign a public IP address to the instance for Internet access. For more information, see AllocatePublicIpAddress.

Step 3: Access the instance metadata URL within the instance to obtain an STS temporary credential

Important

A new STS temporary credential is generated 30 minutes before the current one expires. You can use both STS credentials within the 30-minute period.

  1. Connect to an ECS instance.

    For information about the connection methods, see Connection method overview.

  2. Access http://100.100.100.200/latest/meta-data/ram/security-credentials/EcsRamRoleTest to obtain the STS temporary credential.

    Note

    In this example, the curl command is used to access the preceding URL. The last part of the URL is the RAM role name, which must be replaced with the name that you set. If your instance is a Windows instance, see Obtain instance metadata.

    Sample outputs:

    [root@local ~]# curl http://100.100.100.200/latest/meta-data/ram/security-credentials/EcsRamRoleTest
    {
    "AccessKeyId" : "STS.J8XXXXXXXXXX4",
    "AccessKeySecret" : "9PjfXXXXXXXXXBf2XAW",
    "Expiration" : "2017-06-09T09:17:19Z",
    "SecurityToken" : "CAIXXXXXXXXXXXwmBkleCTkyI+",
    "LastUpdated" : "2017-06-09T03:17:18Z",
    "Code" : "Success"
    }

Step 4: Use SDK for Python to access OSS by using the STS temporary credential

In this example, SDK for Python is used to list 10 files in a specified OSS bucket located in the region where the ECS instance resides through the STS temporary credential.

Prerequisites

  • The ECS instance is connected.

  • The ECS instance is installed with Python. If your instance is a Linux instance, you must install pip.

  • An OSS bucket is created in the region where the ECS instance resides and the name and endpoint of the bucket are obtained.

    In this example, the bucket name is ramroletest, and the endpoint is oss-cn-hangzhou.aliyuncs.com.

Procedure

  1. Run the pip install oss2 command to install OSS SDK for Python.

  2. Run the following commands to test whether SDK for Python can be used to list 10 files in the specified OSS bucket:

    import oss2
    from itertools import islice
    auth = oss2.StsAuth(<AccessKeyId>, <AccessKeySecret>, <SecurityToken>)
    bucket = oss2.Bucket(auth, <Your endpoint>, <Your bucket name>)
    for b in islice(oss2.ObjectIterator(bucket), 10):
      print(b.key)

    Take note of the following items:

    Sample outputs:

    [root@local ~]# python
    Python 2.7.5 (default, Nov  6 2016, 00:28:07)
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import oss2
    >>> from itertools import islice
    >>> auth = oss2.StsAuth("STS.J8XXXXXXXXXX4", "9PjfXXXXXXXXXBf2XAW", "CAIXXXXXXXXXXXwmBkleCTkyI+")
    >>> bucket = oss2.Bucket(auth, "oss-cn-hangzhou.aliyuncs.com", "ramroletest")
    >>> for b in islice(oss2.ObjectIterator(bucket), 10):
    ...     print(b.key)
    ...
    ramroletest.txt
    test.shh