An instance RAM role is a RAM role assigned to an ECS instance. It is a regular service role with an Elastic Compute Service (ECS) instance as its trusted entity. Instance RAM roles allow you to retrieve Security Token Service (STS) tokens as temporary access credentials within an ECS instance, eliminating the need for an AccessKey pair. These temporary credentials enable API calls to other Alibaba Cloud services, enhancing the security of your Alibaba Cloud account's AccessKey pair and supporting fine-grained access control and permission management through RAM.
Advantages
-
Secure and convenient in-instance API call solution: Eliminate the need to configure an AccessKey in your code when your project is on Alibaba Cloud ECS. Instead, leverage ECS capabilities to retrieve temporary STS tokens for API calls, reducing AccessKey exposure risks.
-
Simplified RAM identity switching process: Avoid modifying configurations or code and restarting services when changing the RAM identity for service calls by simply updating the instance RAM role attached to the ECS instance.
-
Fine-grained permission management: Assign specific authorization policies to RAM roles for different ECS instances to achieve detailed access control tailored to your business needs.
Limits
The following restrictions apply when attaching an instance RAM role to an ECS instance:
-
The ECS instances must be within virtual private clouds (VPCs).
-
Only one instance RAM role can be attached to an ECS instance at a time.
Implementation process
If you are using an Alibaba Cloud account for the following operations, no additional permissions are required to configure and use instance RAM roles. If a RAM user or RAM role is performing the operations, grant the necessary permissions to the RAM user or RAM role as follows.
Create a RAM role and attach it to an ECS instance
Create and attach the role in the console
-
Log on to the RAM console and create a RAM role with the necessary permissions.
-
Create a RAM role with an Alibaba Cloud service as the trusted entity.
Select Identity Management > Roles and click Create Role. Follow the on-screen instructions to finalize the creation of the role. Pay attention to the following parameters, though you may configure additional parameters as necessary. For more information, see Create a regular service role:
-
Type of trusted entity: Select Alibaba Cloud Service .
-
Name of trusted entity: Select Elastic Compute Service .
-
-
Assign permissions to the created RAM role.
Grant system or custom policies to the RAM role for resource access or management. For instance, you can assign the system policy AliyunOSSReadOnlyAccess to the RAM role.
NoteIf system policies do not meet your needs, create custom policies for the RAM role. For more information, see Create a custom policy.
-
-
Attach the RAM role to an ECS instance.
Log on to the ECS console.
In the left-side navigation pane, choose .
In the top navigation bar, select the region and resource group to which the resource belongs.
-
Find the ECS instance you want to manage and choose
. -
In the dialog box, select the RAM role for the instance you created and click OK.
Create and attach the role by calling API operations
-
Create a RAM role and assign permissions.
-
Use the CreateRole operation to create a RAM role.
Parameters in the trust policy (AssumeRolePolicyDocument):
{ "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" }
-
(Optional) Use the CreatePolicy operation to create a policy.
Skip this step if you already have a suitable policy for the RAM role.
The
PolicyDocument
must be set as follows:{ "Statement": [ { "Action": [ "oss:Get*", "oss:List*" ], "Effect": "Allow", "Resource": "*" } ], "Version": "1" }
-
Grant permissions to the instance RAM role by calling the AttachPolicyToRole operation.
-
-
Attach the RAM role to the ECS instance using the AttachInstanceRamRole operation.
Obtain temporary access credentials for an instance RAM role
Access the metadata service within an ECS instance to obtain temporary access credentials. For details on metadata, refer to Instance metadata.
Method 1: Obtain temporary access credentials by using the Credentials tool
The Credentials tool encapsulates the logic for calling the ECS metadata service to retrieve STS tokens as temporary access credentials and supports the periodic updating of these credentials.
Python
-
Install the Credentials tool.
NoteThe version of alibabacloud_credentials must be 0.3.6 or later.
pip install alibabacloud_credentials
-
Configure the ECS instance to use the instance RAM role to retrieve 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 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. role_name='<RoleName>' ) credentialsClient = CredClient(credentialConfig)
Java
-
Add the credentials dependency.
NoteThe 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>LATEST</version> </dependency>
-
Configure the ECS instance to use the instance RAM role to retrieve 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); } }
Go
-
Install the Credentials tool.
NoteThe 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 manage dependencies with
dep
, execute the following command.dep ensure -add github.com/aliyun/credentials-go
-
-
Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.
package main import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func _main(args []*string) { credentialsConfig := new(credentials.Config). 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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. SetRoleName("<RoleName>") credentialClient, err := credentials.NewCredential(credentialsConfig) if err != nil { panic(_err) } }
Node.js
-
Install the Credentials tool.
NoteThe version of credentials must be 2.3.1 or later.
npm install @alicloud/credentials
-
Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.
const Credential = require('@alicloud/credentials'); const credentialsConfig = new Credential.Config({ type: '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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. roleName: '<RoleName>', }); const cred = new Credential.default(credentialsConfig);
.NET
-
Install the Credentials tool.
NoteThe version of credentials must be 1.4.2 or later.
dotnet add package Aliyun.Credentials
-
Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.
using Aliyun.Credentials.Models; namespace credentials_demo { class Program { static void Main(string[] args) { var config = new Config() { Type = "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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. RoleName = "<RoleName>" } } } }
PHP
-
Install the Credentials tool.
NoteThe version of credentials must be 1.2.0 or later.
composer require alibabacloud/credentials
-
Configure the ECS instance to use the instance RAM role to retrieve temporary access credentials.
<?php use AlibabaCloud\Credentials\Credential; use AlibabaCloud\Credentials\Credential\Config; $credConfig = new Config([ 'type' => '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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. 'roleName' => '<RoleName>', ]);
Method 2: Obtain temporary access credentials by using shell commands
The metadata service provides an HTTP endpoint for obtaining temporary access credentials.
Security hardening mode
-
Linux instance
# Obtain access credentials from 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 a temporary authorization token for 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 access credentials from 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 a temporary authorization token 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/<Instance RAM role name>
<Validity period of the metadata server access credentials>:
Before obtaining a temporary authorization token for the instance RAM role, retrieve access credentials from the metadata server and set their validity period to enhance security. After the validity period expires, you must re-obtain the access credentials to continue receiving the temporary authorization token for the instance RAM role.
Valid values range from 1 to 21600 seconds. For more details, see Instance metadata.
<Instance RAM role name>
: Replace this placeholder with the actual name of the instance RAM role, such as EcsRamRole
.
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/Invoke-RestMethod http://100.100.100.200/latest/meta-data/ram/security-credentials/<Instance RAM role name>
<Instance RAM role name>
Replace this placeholder with the actual instance RAM role name, such as EcsRamRoleDocumentTesting.
Below is a sample response with the following parameters:
-
AccessKeyId
,AccessKeySecret
, andSecurityToken
comprise a temporary access token. -
Expiration
: The validity period of the temporary authorization token.{ "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
This example demonstrates how to call API operations using an instance RAM role. A Python application, deployed on a Linux ECS instance, utilizes the attached instance RAM role to retrieve 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 credential type. 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 = 'oss-cn-beijing.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)
Other operations
Detach or change the instance RAM role of an ECS instance
Detach or change the role in the console
Log on to the ECS console.
In the left-side navigation pane, choose .
In the top navigation bar, select the region and resource group to which the resource belongs.
-
Locate the ECS instance you want to manage and select
.-
To detach the instance RAM role, select Operation Type and then choose Detach. Click OK.
-
To change the instance RAM role, select Operation Type and then choose Attach. Pick the necessary instance RAM role and click OK to finalize the change.
-
Detach or change the role by calling API operations
-
Detach the instance RAM role: Call the DetachInstanceRamRole operation.
-
Change the instance RAM role:
-
Call the DetachInstanceRamRole operation to detach the current RAM role.
-
Call the AttachInstanceRamRole operation to attach a new RAM role to the instance.
-
References
-
If you have a self-managed application deployed on an ECS instance, you can enhance security by attaching an instance RAM role to the instance for KMS access. For more information, see Use an instance RAM role to securely access KMS.
-
Should an ECS instance no longer need certain permissions, you can remove those permissions from the instance RAM role associated with it. For more information, see Revoke permissions from a RAM role.
-
Accessing Alibaba Cloud OpenAPI with hard-coded plaintext AccessKey pairs can lead to security breaches if code repositories are not properly permissioned. It is advisable to use access credentials rather than hard-coding AccessKey pairs. For more information, see Best practices for using access credentials to access Alibaba Cloud OpenAPI.