Attach an instance RAM role to an ECS instance to obtain STS tokens for calling other Alibaba Cloud APIs without exposing an AccessKey pair.
Benefits
-
Secure API calls: Obtain STS tokens from ECS without embedding an AccessKey pair in your code, reducing the risk of credential leaks.
-
Simplified identity switching: Switch the RAM identity by changing the instance RAM role instead of modifying code or restarting the service.
-
Fine-grained access control: Assign RAM roles with specific policies to different ECS instances for granular permission management.
Limitations
You can attach only one RAM role to an ECS instance.
Procedure
If you use a RAM user or RAM role, grant the required permissions to that identity first.
Create a RAM role and attach it to an ECS instance
Console
-
Log on to the RAM console to create a RAM role and attach policies.
-
Create a RAM role for a trusted Alibaba Cloud service.
Select Identities > Roles, click Create Role, and follow the on-screen instructions. Note the following parameters. See Create a RAM role for a trusted Alibaba Cloud service:
-
Principal Type: Select Cloud Service.
-
Principal Name, select ECS.
-
-
Grant permissions to the created RAM role.
Attach a system policy or a custom policy to the RAM role. For example, attach the AliyunOSSReadOnlyAccess system policy.
To create custom policies, see Create a custom policy.
-
-
Attach the RAM role to an ECS instance.
Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target resource.
-
Find the target ECS instance, and choose .
-
In the dialog box, select the instance RAM role that you created, and then click OK.
API
-
Create a RAM role and attach policies.
-
Call the CreateRole operation to create a RAM role.
Set AssumeRolePolicyDocument to the following trust policy:
{ "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" } -
(Optional) Call the CreatePolicy operation to create an access policy.
Skip this step if you already have a suitable access policy.
Set
PolicyDocumentas follows:{ "Statement": [ { "Action": [ "oss:Get*", "oss:List*" ], "Effect": "Allow", "Resource": "*" } ], "Version": "1" } -
Call the AttachPolicyToRole operation to attach the policy to the RAM role.
-
-
Call the AttachInstanceRamRole operation to attach the RAM role to the ECS instance.
Obtain temporary credentials
Obtain temporary credentials from within an ECS instance by accessing the metadata service. Credential validity is managed automatically. See Instance metadata.
Use the Credentials tool
The Credentials tool wraps the ECS IMDS to obtain and periodically refresh STS tokens.
Python
-
Install the Credentials tool.
Security hardening mode requires alibabacloud_credentials 0.3.6 or later.
pip install alibabacloud_credentials -
Configure the ECS instance RAM role 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 normal mode (IMDSv1). disable_imds_v1=False, ) credentialsClient = CredClient(credentialsConfig)
Java
-
Add the credentials dependency.
Security hardening mode requires credentials-java 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 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 normal mode (IMDSv1). credentialConfig.setDisableIMDSv1(true); Client credentialClient = new Client(credentialConfig); } }
Go
-
Install the Credentials tool.
Security hardening mode requires credentials-go 1.3.10 or later.
-
Use
go getto install:go get -u github.com/aliyun/credentials-go -
If you use
depto manage dependencies:dep ensure -add github.com/aliyun/credentials-go
-
-
Configure the ECS instance RAM role 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 normal mode (IMDSv1). SetDisableIMDSv1(true) credentialClient, err := credentials.NewCredential(credentialsConfig) if err != nil { panic(err) } }
Node.js
-
Install the Credentials tool.
Security hardening mode requires credentials 2.3.1 or later.
npm install @alicloud/credentials -
Configure the ECS instance RAM role 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 normal mode (IMDSv1). disableIMDSv1: true, }); const cred = new Credential.default(credentialsConfig);
.NET
-
Install the Credentials tool.
Security hardening mode requires credentials 1.4.2 or later.
dotnet add package Aliyun.Credentials -
Configure the ECS instance RAM role 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 normal mode (IMDSv1). DisableIMDSv1 = true } } } }
PHP
-
Install the Credentials tool.
Security hardening mode requires credentials 1.2.0 or later.
composer require alibabacloud/credentials -
Configure the ECS 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 normal mode (IMDSv1). 'disableIMDSv1' => true, ]);
Use shell commands
Retrieve temporary credentials through the metadata service HTTP endpoint.
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>: The validity period of the metadata server access token. The token must be obtained before retrieving temporary credentials. After expiration, obtain a new token.
Valid values: 1 to 21600. Unit: seconds. 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 these commands, the Cloud Assistant Agent must meet the following minimum version requirements:
|
Platform |
Minimum 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/<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.
Sample response:
-
The temporary access token consists of
AccessKeyId,AccessKeySecret, andSecurityToken. -
Expiration: The expiration time of the temporary credentials.{ "AccessKeyId" : "STS.*******6YSE", "AccessKeySecret" : "aj******jDU", "Expiration" : "2017-11-01T05:20:01Z", "SecurityToken" : "CAISng********", "LastUpdated" : "2023-07-18T14:17:28Z", "Code" : "Success" }
Use the CLI
The CLI wraps the ECS IMDS to obtain and automatically refresh STS tokens.
Security hardening mode requires CLI 3.0.248 or later.
-
Install the CLI.
-
Configure identity credentials.
Configure credential information. Replace <ProfileName> with the name of your configuration.
aliyun configure --profile <ProfileName> --mode EcsRamRoleFollow the prompts to enter the required information. See Configure credentials.
-
Call an API operation.
For example, query the list of ECS instances:
aliyun ecs DescribeInstancesSee Command structure.
Example: Call an API with an instance RAM role
The following Python example downloads a file from OSS using an instance RAM role on a Linux ECS instance.
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', # 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 an instance RAM role
Console
Go to ECS console - Instances. In the top-left corner, select the region and resource group for the target resource.
-
Find the ECS instance that you want to manage and choose .
-
To detach an instance RAM role: Set Action to Detach and click Confirm.
-
To change the instance RAM role: Set Action to Attach, select the desired instance RAM role, and then click Confirm.
-
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
-
To access Key Management Service (KMS) from a custom application on an ECS instance, see Use the instance RAM role attached to an ECS instance to securely access KMS.
-
To remove specific permissions, revoke permissions from a RAM role.
-
Do not hard-code a plaintext AccessKey when calling Alibaba Cloud OpenAPI. Use access credentials instead to avoid exposure through improper code repository management.
> Instance Settings > Attach/Detach RAM Role