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 principal 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.
Create an instance RAM role and attach the RAM role to an ECS instance
Use the consoles
Log on to the RAM console, create an instance RAM role, and grant permissions to the RAM role.
Create an instance RAM role whose principal 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.
Principal Type: Select Cloud Service.
Principal Name: Select Elastic Compute Service.
Grant permissions to the RAM role.
Attach system policies or custom policies to the RAM role to grant it permissions for accessing or managing specific resources. For example, you can grant the AliyunOSSReadOnlyAccess custom policy to the RAM role.
NoteIf the system policies do not meet your business requirements, you can create custom policies for the RAM role.
Attach the instance 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 of the resource that you want to manage.
Find the ECS instance to which you want to attach the instance RAM role and choose
in the Actions column.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
Create an instance RAM role and grant permissions to the RAM role.
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" }
(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" }
Call the AttachPolicyToRole operation to attach the policy to the instance RAM role.
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 within an application
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.
Python
Install the Credentials tool.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the alibabacloud_credentials package must be 0.3.6 or later.
pip install alibabacloud_credentials
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 credentialsConfig = 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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. role_name='<role_name>', # Optional. Default value: False. True: forcefully obtains data in security hardening mode. False: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. enable_imds_v1=True, ) credentialsClient = CredClient(credentialsConfig)
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
Java
Add the dependencies of credentials.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the credentials-java package 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>0.3.10</version> </dependency>
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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. credentialConfig.setRoleName("<RoleName>"); # Optional. Default value: false. true: forcefully obtains data in security hardening mode. false: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. credentialConfig.setDisableIMDSv1(true); Client credentialClient = new Client(credentialConfig); } }
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
Go
Install the Credentials tool.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the credentials-go package must be 1.3.10 or later.
Run the
go get
command to download and install the Credentials tool.go get -u github.com/aliyun/credentials-go
If you use the
dep
utility to manage dependencies, run the following command:dep ensure -add github.com/aliyun/credentials-go
Configure the ECS instance to use the instance RAM role to obtain 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 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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. SetRoleName("<RoleName>"). // Optional. Default value: false. true: forcefully obtains data in security hardening mode. false: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. SetDisableIMDSv1(true) credentialClient, err := credentials.NewCredential(credentialsConfig) if err != nil { panic(err) } }
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
Node.js
Install the Credentials tool.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the credentials package must be 2.3.1 or later.
npm install @alicloud/credentials
Configure the ECS instance to use the instance RAM role to obtain temporary access credentials.
const Credential = require('@alicloud/credentials'); const credentialsConfig = new Credential.Config({ 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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. roleName: '<RoleName>', // Optional. Default value: false. true: forcefully obtains data in security hardening mode. false: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. disableIMDSv1: true, }); const cred = new Credential.default(credentialsConfig);
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
.NET
Install the Credentials tool.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the credentials package must be 1.4.2 or later.
dotnet add package Aliyun.Credentials
Configure the ECS instance to use the instance RAM role to obtain 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 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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. RoleName = "<RoleName>", // Optional. Default value: false. true: forcefully obtains data in security hardening mode. false: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. DisableIMDSv1 = true } } } }
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
PHP
Install the Credentials tool.
NoteIf you obtain temporary access credentials in security hardening mode, the version of the credentials package must be 1.2.0 or later.
composer require alibabacloud/credentials
Configure the ECS instance to use the instance RAM role to obtain 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 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. You can configure the name of the instance RAM role in the ALIBABA_CLOUD_ECS_METADATA environment variable and reference the environment variable. 'roleName' => '<RoleName>', // Optional. Default value: false. true: forcefully obtains data in security hardening mode. false: attempts to obtain data in security hardening mode and then in normal mode (IMDSv1) if data obtaining fails in security hardening mode. 'disableIMDSv1' => true, ]);
For more information and examples, see Method 5: Use the RAM role of an ECS instance.
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
.
If you use Cloud Assistant to run the preceding commands, the version of Cloud Assistant Agent must be one of the versions in the following table or later.
Operating system | Earliest 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/<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
, andSecurityToken
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" }
Method 3: Use Alibaba Cloud CLI
You can use Alibaba Cloud CLI to obtain STS tokens as temporary access credentials by calling the ECS metadata service. The credentials can be refreshed periodically.
If you obtain temporary access credentials in security hardening mode, the version of Alibaba Cloud CLI must be 3.0.248 or later.
Perform the following steps:
Install Alibaba Cloud CLI.
Run the following command to configure a credential. Replace <ProfileName> with the actual profile name.
aliyun configure --profile <ProfileName> --mode EcsRamRole
The preceding command is an interactive command. You must enter information as prompted. For more information, see EcsRamRole.
Call an API operation.
For example, run the following Alibaba Cloud CLI command to query ECS instances:
aliyun ecs DescribeInstances
For more information about Alibaba Cloud CLI commands, see Command syntax.
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 = 'oss-cn-beijing.aliyuncs.com' # Specify the Internet 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 an instance RAM role
Use the ECS 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 of the resource that you want to manage.
Find the ECS instance that you want to manage and choose
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.
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:
Call the DettachInstanceRamRole operation to detach the instance RAM role from the ECS instance.
Call the AttachInstanceRamRole operation to attach a different instance RAM role to the ECS instance.
References
If your self-managed application is deployed on an ECS instance, you can attach an instance RAM role to the ECS instance and use the instance RAM role to access Key Management Service (KMS) from the instance. For more information, see Use the instance RAM role attached to an ECS instance to securely access KMS.
If an ECS instance no longer requires specific permissions, you can revoke the permissions from the instance RAM role that is attached to the instance. For more information, see Revoke permissions from a RAM role.
If you hard code a plaintext AccessKey pair in the code that you use to call API operations of Alibaba Cloud, the AccessKey pair may be leaked due to improper permission management of the code repository. To call the API operations of Alibaba Cloud, we recommend that you use access credentials instead of a hard-coded AccessKey pair. For more information, see Best practices for using an access credential to call API operations.