An instance Resource Access Management (RAM) role is a service role that you can attach to an Elastic Compute Service (ECS) instance. The trusted entity of an instance RAM role is ECS. You can use an instance RAM role to obtain a Security Token Service (STS) token from within an ECS instance without providing an AccessKey pair. You can then use the STS token to call the API operations of other Alibaba Cloud services. You can obtain the temporary identity credential only from within an instance. This eliminates the need to configure an AccessKey pair, which enhances the security of your Alibaba Cloud account's AccessKey pair and lets you implement fine-grained permission management using RAM.
Benefits
Secure and convenient API calls within instances: When your project is deployed on Alibaba Cloud ECS, you can use an instance RAM role to obtain an STS token to call APIs instead of configuring an AccessKey pair in your code. This reduces the risk of AccessKey pair leaks.
Simplified RAM identity switching: If you use a traditional AccessKey pair, you must modify the configuration or code and restart the service to change the RAM identity that calls the service. If you use an instance RAM role, you only need to change the RAM role that is attached to the ECS instance to switch identities. No other changes are required.
Fine-grained permission management: You can assign RAM roles with specific authorization policies to different ECS instances. This lets you implement fine-grained access control as needed.
Limits
You can attach only one RAM role to an ECS instance.
Procedure
If you use a RAM user or RAM role to perform the following operations, grant the required permissions to that identity.
Create a RAM role and attach it to an ECS instance
Create and attach a role in the console
Log on to the RAM console to create a RAM role and grant permissions.
Create a RAM role for a trusted Alibaba Cloud service.
Choose Identities > Roles, click Create Role, and follow the on-screen instructions to create the role. Note the following parameters and configure other parameters as needed. For more information, see Create a service role:
For Trusted Entity Type, select Alibaba Cloud Service.
For Trusted Service, select Elastic Compute Service.
Grant permissions to the created RAM role.
Attach a system policy or a custom policy to the RAM role to grant it the required resource access or operation permissions. For example, grant the AliyunOSSReadOnlyAccess system policy to the RAM role.
If the system policies do not meet your requirements, you can grant permissions to a RAM role by creating a custom policy. For more information, see Create a custom policy.
Attach the RAM role to an ECS instance.
Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.
Find the target ECS instance and choose .
In the dialog box, select the instance RAM role and click OK.
Creation via API and granting
Create a RAM role and grant permissions.
Call the CreateRole operation to create a RAM role.
Parameter for the trust policy (AssumeRolePolicyDocument):
{ "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" }(Optional) Call the CreatePolicy operation to create a new access policy.
If you have an available access policy, you can skip this step.
Set the
PolicyDocumentparameter as follows:{ "Statement": [ { "Action": [ "oss:Get*", "oss:List*" ], "Effect": "Allow", "Resource": "*" } ], "Version": "1" }Call the AttachPolicyToRole operation to grant permissions to the instance RAM role.
Call the AttachInstanceRamRole operation to attach the RAM role to the ECS instance.
Obtain temporary identity credentials for an instance RAM role
You can obtain temporary access credentials from within an ECS instance by accessing the Instance Metadata Service (IMDS). The validity period of the temporary access credentials is automatically managed. For more information about metadata, see Instance metadata.
Method 1: Use the Credentials tool in a program
The Credentials tool encapsulates the logic of calling the ECS IMDS to obtain an STS token. It also supports periodic renewal.
Python
Install the Credentials tool.
To retrieve temporary identity credentials in security hardening mode, the version of alibabacloud_credentials must be 0.3.6 or later.
pip install alibabacloud_credentialsConfigure the RAM role of the ECS instance as the access credential.
from alibabacloud_credentials.client import Client as CredClient from alibabacloud_credentials.models import Config as CredConfig credentialsConfig = CredConfig( type='ecs_ram_role', # Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. role_name='<role_name>', # Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). disable_imds_v1=False, ) credentialsClient = CredClient(credentialsConfig)For more information and invocation examples, see Method 5: ECS instance RAM role.
Java
Add the credentials dependency.
To retrieve temporary identity credentials in security hardening mode, the 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>0.3.10</version> </dependency>You can configure the ECS instance to use its instance RAM role as the access credential.
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. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. credentialConfig.setRoleName("<RoleName>"); // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). credentialConfig.setDisableIMDSv1(true); Client credentialClient = new Client(credentialConfig); } }For more information and invocation examples, see Method 5: ECS instance RAM role.
Go
Install the Credentials tool.
To retrieve temporary identity credentials in security hardening mode, the version of credentials-go must be 1.3.10 or later.
Use
go getto download and install the tool.go get -u github.com/aliyun/credentials-goIf you use
depto manage dependencies, run the following command.dep ensure -add github.com/aliyun/credentials-go
Configure the instance RAM role of the ECS instance as the access credential.
package main import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func _main(args []*string) { credentialsConfig := new(credentials.Config). SetType("ecs_ram_role"). // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. SetRoleName("<RoleName>"). // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). SetDisableIMDSv1(true) credentialClient, err := credentials.NewCredential(credentialsConfig) if err != nil { panic(err) } }For more information and invocation examples, see Method 5: Use an ECS instance RAM role.
Node.js
Install the Credentials tool.
To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 2.3.1 or later.
npm install @alicloud/credentialsConfigure the instance RAM role of the ECS instance as the access credential.
const Credential = require('@alicloud/credentials'); const credentialsConfig = new Credential.Config({ type: 'ecs_ram_role', // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. roleName: '<RoleName>', // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). disableIMDSv1: true, }); const cred = new Credential.default(credentialsConfig);For more information and invocation examples, see Method 5: Use an ECS instance RAM role.
.NET
Install the Credentials tool.
To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 1.4.2 or later.
dotnet add package Aliyun.CredentialsConfigure the instance RAM role of the ECS instance as the access credential.
using Aliyun.Credentials.Models; namespace credentials_demo { class Program { static void Main(string[] args) { var config = new Config() { Type = "ecs_ram_role", // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. RoleName = "<RoleName>", // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). DisableIMDSv1 = true } } } }For more information and invocation examples, see Method 5: Use an ECS instance RAM role.
PHP
Install the Credentials tool.
To retrieve temporary identity credentials in security hardening mode, the version of credentials must be 1.2.0 or later.
composer require alibabacloud/credentialsConfigure the ECS instance to use its instance RAM role as the access credential.
<?php use AlibabaCloud\Credentials\Credential; use AlibabaCloud\Credentials\Credential\Config; $credConfig = new Config([ 'type' => 'ecs_ram_role', // Optional. The name of the instance RAM role. If you do not specify this parameter, the name is automatically retrieved. We recommend that you specify this parameter to reduce requests. You can also set the role name using the ALIBABA_CLOUD_ECS_METADATA environment variable. 'roleName' => '<RoleName>', // Optional. The default value is false. If you set this to true, security hardening mode is enforced. If you set this to false, the system first tries to retrieve credentials in security hardening mode. If the attempt fails, the system tries again in NAT mode (IMDSv1). 'disableIMDSv1' => true, ]);For more information, see Method 5: Use an ECS instance RAM role.
Method 2: Use shell commands
The metadata service provides an HTTP endpoint to retrieve temporary access credentials.
Security hardening mode
Linux instance
# Obtain the access token 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_token>"` # Obtain the temporary access credentials of 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 the access token of the metadata server for authentication. $token = Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "<validity_period_of_the_metadata_server_access_token>"} -Method PUT -Uri http://100.100.100.200/latest/api/token # Obtain the temporary access credentials of 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_token>: Before you retrieve the temporary access credentials of the instance RAM role, you must first obtain an access token for the metadata server. This token has a configurable validity period to enhance data security. After the token expires, you must obtain a new one before you can retrieve the temporary access credentials.
Valid values: 1 to 21600. Unit: seconds. For more information, see Instance metadata.
<instance_RAM_role_name>: Replace this with the name of your instance RAM role. For example, EcsRamRole.
If you use Cloud Assistant to run the preceding commands, make sure that the Cloud Assistant Agent meets the following minimum version requirements:
Platform | Cloud Assistant Agent version number |
windows | 2.1.3.857 |
linux | 2.2.3.857 |
linux arm | 2.4.3.857 |
freebsd | 2.3.3.857 |
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/ram/security-credentials/<instance_RAM_role_name>Replace
<instance_RAM_role_name>with the name of your instance RAM role. For example, EcsRamRoleDocumentTesting.
The following is a sample response:
The temporary access credentials consist of the
AccessKeyId,AccessKeySecret, andSecurityTokenvalues.Expiration: The expiration time of the temporary access credentials.{ "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 the Alibaba Cloud CLI
The command-line interface (CLI) supports calling the ECS IMDS to obtain an STS token. It also supports periodic and automatic refreshes.
To retrieve temporary identity credentials in security hardening mode, the version of the CLI must be 3.0.248 or later.
Install the CLI.
Configure identity credentials.
Run the following command to configure credential information. Replace <ProfileName> with the name of your configuration.
aliyun configure --profile <ProfileName> --mode EcsRamRoleThis is an interactive command. Follow the prompts to enter the required information. For more information, see Configure credentials.
Call an API operation.
For example, use the CLI to query the list of ECS instances.
aliyun ecs DescribeInstancesFor more information about CLI commands, see Command structure.
Use an instance RAM role to call an API
The following example shows how to use an instance RAM role. A Python application deployed on a Linux ECS instance calls an OSS API operation to download a file.
pip install oss2
pip install alibabacloud_credentialsimport 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', # The type of access credential. This value is fixed as ecs_ram_role.
role_name=role_name
)
cred = Client(config)
credentials_provider = CredentialProviderWarpper(cred)
auth = oss2.ProviderAuth(credentials_provider)
# Initialize the OSS Bucket object.
bucket = oss2.Bucket(auth, endpoint, bucket_name)
# Download the image to the local instance.
bucket.get_object_to_file(object_key, local_file)
print("Image downloaded successfully")
if __name__ == "__main__":
# Define global variables.
role_name = 'role_name' # Replace with the name of your instance RAM role.
bucket_name = 'bucket_name' # Replace with your bucket name.
endpoint = 'oss-cn-beijing.aliyuncs.com' # Replace with the public endpoint of your OSS bucket.
object_key = 'testfolder/example.png' # Replace with the full path of the image that you want to download from OSS. Do not include the bucket name.
local_file = '/localpath/to/image.png' # Replace with the root path on the ECS instance where you want to store the image, and define the image name.
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 a role in the console
Go to ECS console - Instances. In the top navigation bar, select the target region and resource group.
Find the ECS instance that you want to manage, and choose .
To detach the instance RAM role, select Detach for Operation Type and then click OK.
To change the instance RAM role, set Operation Type to Attach, select the required instance RAM role, and then click OK.
Detach or change a role using the API
To detach an instance RAM role, call the DetachInstanceRamRole operation.
To change an instance RAM role:
Call the DetachInstanceRamRole operation to detach the current instance RAM role.
Call the AttachInstanceRamRole operation to attach the new RAM role to the instance.
References
If your custom application is deployed on an Alibaba Cloud ECS instance and needs to access KMS, see Use an instance RAM role to securely access KMS.
If an ECS instance no longer requires specific permissions, you can revoke permissions from a RAM role.
When you access Alibaba Cloud OpenAPI, do not hard-code a plaintext AccessKey. Improper permission management of your code repository can expose your AccessKey. Instead, configure your application to use access credentials to access Alibaba Cloud OpenAPI.
> Instance Settings > Attach/Detach RAM Role