Anexe uma função de RAM da instância a uma instância ECS para obter tokens STS e chamar outras APIs do Alibaba Cloud sem expor um par de AccessKey.
Benefícios
Chamadas de API seguras: Obtenha tokens STS diretamente do ECS sem incorporar um par de AccessKey no código, reduzindo o risco de vazamento de credenciais.
Troca simplificada de identidade: Alterne a identidade RAM modificando a função de RAM da instância, evitando alterações no código ou reinicializações do serviço.
Controle de acesso refinado: Atribua funções de RAM com políticas específicas a diferentes instâncias ECS para gerenciar permissões granularmente.
Limitações
É possível anexar apenas uma função de RAM por instância ECS.
Procedimento
Se você utilizar um usuário RAM ou uma função de RAM, conceda as permissões necessárias a essa identidade antes de prosseguir.
Criar uma função de RAM e anexá-la a uma instância ECS
Console
-
Faça login no console do RAM para criar uma função de RAM e anexar políticas.
-
Crie uma função de RAM para um serviço confiável do Alibaba Cloud.
Selecione Identities > Roles, clique em Create Role e siga as instruções na tela. Observe os parâmetros a seguir. Consulte Criar uma função de RAM para um serviço confiável do Alibaba Cloud:
Principal Type: Selecione Cloud Service.
Em Principal Name, selecione ECS.
-
Conceda permissões à função de RAM criada.
Anexe uma política do sistema ou personalizada à função de RAM. Por exemplo, anexe a política do sistema AliyunOSSReadOnlyAccess.
Para criar políticas personalizadas, consulte Criar uma política personalizada .
-
-
Anexe a função de RAM a uma instância ECS.
Acesse o console do ECS - Instâncias. No canto superior esquerdo, selecione a região e o grupo de recursos do recurso de destino.
Localize a instância ECS desejada e escolha .
Na caixa de diálogo, selecione a função de RAM da instância criada e clique em OK.
API
-
Crie uma função de RAM e anexe políticas.
-
Chame a operação CreateRole para criar uma função de RAM.
Defina AssumeRolePolicyDocument com a seguinte política de confiança:
{ "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "ecs.aliyuncs.com" ] } } ], "Version": "1" } -
(Opcional) Chame a operação CreatePolicy para criar uma política de acesso.
Ignore esta etapa se já possuir uma política de acesso adequada.
Defina
PolicyDocumentconforme abaixo:{ "Statement": [ { "Action": [ "oss:Get*", "oss:List*" ], "Effect": "Allow", "Resource": "*" } ], "Version": "1" } Chame a operação AttachPolicyToRole para anexar a política à função de RAM.
-
Chame a operação AttachInstanceRamRole para anexar a função de RAM à instância ECS.
Obter credenciais temporárias
Obtenha credenciais temporárias dentro de uma instância ECS acessando o serviço de metadados. O sistema gerencia a validade das credenciais automaticamente. Consulte Metadados da instância.
Usar a ferramenta Credentials
A ferramenta Credentials encapsula o IMDS do ECS para obter e atualizar periodicamente os tokens STS.
Python
-
Instale a ferramenta Credentials.
O modo de reforço de segurança requer alibabacloud_credentials 0.3.6 ou posterior.
pip install alibabacloud_credentials -
Configure a função de RAM da instância ECS como credencial de acesso.
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)Consulte Método 5: Função de RAM da instância ECS.
Java
-
Adicione a dependência de credenciais.
O modo de reforço de segurança requer credentials-java 0.3.10 ou posterior.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java --> <dependency> <groupId>com.aliyun</groupId> <artifactId>credentials-java</artifactId> <version>0.3.10</version> </dependency> -
Configure a função de RAM da instância ECS como credencial de acesso.
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); } }Consulte Método 5: Função de RAM da instância ECS.
Go
-
Instale a ferramenta Credentials.
O modo de reforço de segurança requer credentials-go 1.3.10 ou posterior.
-
Use
go getpara instalar:go get -u github.com/aliyun/credentials-go -
Se utilizar
deppara gerenciar dependências:dep ensure -add github.com/aliyun/credentials-go
-
-
Configure a função de RAM da instância ECS como credencial de acesso.
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) } } -
Instale a ferramenta Credentials.
O modo de reforço de segurança requer credentials 2.3.1 ou posterior.
npm install @alicloud/credentials -
Configure a função de RAM da instância ECS como credencial de acesso.
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);Consulte Método 5: Uso de uma função de RAM da instância ECS.
-
Instale a ferramenta Credentials.
O modo de reforço de segurança requer credentials 1.4.2 ou posterior.
dotnet add package Aliyun.Credentials -
Configure a função de RAM da instância ECS como credencial de acesso.
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 } } } }Consulte Método 5: Uso de uma função de RAM da instância ECS.
-
Instale a ferramenta Credentials.
O modo de reforço de segurança requer credentials 1.2.0 ou posterior.
composer require alibabacloud/credentials -
Configure a função de RAM da instância ECS como credencial de acesso.
<?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, ]);Consulte Método 5: Uso de uma função de RAM da instância ECS.
-
Instância Linux
# 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> -
Instância Windows (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> -
Instância Linux
curl http://100.100.100.200/latest/meta-data/ram/security-credentials/<instance_RAM_role_name> -
Instância Windows (PowerShell)
Invoke-RestMethod http://100.100.100.200/latest/meta-data/ram/security-credentials/<instance_RAM_role_name>Substitua <instance_RAM_role_name> pelo nome da sua função de RAM da instância. Por exemplo, EcsRamRoleDocumentTesting.
O token de acesso temporário consiste em
AccessKeyId,AccessKeySecreteSecurityToken.-
Expiration: Horário de expiração das credenciais temporárias.{ "AccessKeyId" : "STS.*******6YSE", "AccessKeySecret" : "aj******jDU", "Expiration" : "2017-11-01T05:20:01Z", "SecurityToken" : "CAISng********", "LastUpdated" : "2023-07-18T14:17:28Z", "Code" : "Success" } -
Instale a CLI.
-
Configure as credenciais de identidade.
Configure as informações da credencial. Substitua <ProfileName> pelo nome da sua configuração.
aliyun configure --profile <ProfileName> --mode EcsRamRoleSiga as instruções para inserir as informações necessárias. Consulte Configurar credenciais.
-
Chame uma operação de API.
Por exemplo, consulte a lista de instâncias ECS:
aliyun ecs DescribeInstancesConsulte Estrutura de comandos.
Acesse o console do ECS - Instâncias. No canto superior esquerdo, selecione a região e o grupo de recursos do recurso de destino.
-
Localize a instância ECS que deseja gerenciar e escolha .
Para desanexar uma função de RAM da instância: Defina Action como Detach e clique em Confirm.
Para alterar a função de RAM da instância: Defina Action como Attach, selecione a função de RAM da instância desejada e clique em Confirm.
Para desanexar uma função de RAM da instância, chame a operação DetachInstanceRamRole.
-
Para alterar uma função de RAM da instância:
Chame a operação DetachInstanceRamRole para desanexar a função de RAM da instância atual.
Chame a operação AttachInstanceRamRole para anexar a nova função de RAM à instância.
Para acessar o Key Management Service (KMS) a partir de uma aplicação personalizada em uma instância ECS, consulte Usar a função de RAM da instância anexada a uma instância ECS para acessar o KMS com segurança.
Para remover permissões específicas, revogue as permissões de uma função de RAM.
Não codifique rigidamente (hard-code) um AccessKey em texto simples ao chamar a OpenAPI do Alibaba Cloud. Utilize credenciais de acesso para evitar exposição devido ao gerenciamento inadequado de repositórios de código.
Node.js
.NET
PHP
Usar comandos shell
Recupere credenciais temporárias pelo endpoint HTTP do serviço de metadados.
Modo de reforço de segurança
<validity_period_of_the_metadata_server_access_token>: Período de validade do token de acesso ao servidor de metadados. Obtenha o token antes de recuperar as credenciais temporárias. Após a expiração, obtenha um novo token.
Valores válidos: 1 a 21600. Unidade: segundos. Consulte Metadados da instância.
<instance_RAM_role_name>: Substitua pelo nome da sua função de RAM da instância. Por exemplo, EcsRamRole.
Ao executar esses comandos com o Cloud Assistant, o Agente do Cloud Assistant deve atender aos seguintes requisitos mínimos de versão:
|
Plataforma |
Versão mínima do Agente do Cloud Assistant |
|
windows |
2.1.3.857 |
|
linux |
2.2.3.857 |
|
linux arm |
2.4.3.857 |
|
freebsd |
2.3.3.857 |
Modo normal
Exemplo de resposta:
Usar a CLI
A CLI encapsula o IMDS do ECS para obter e atualizar automaticamente os tokens STS.
O modo de reforço de segurança requer a CLI 3.0.248 ou posterior.
Exemplo: Chamar uma API com uma função de RAM da instância
O exemplo a seguir em Python baixa um arquivo do OSS usando uma função de RAM da instância em uma instância ECS Linux.
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)
> Instance Settings > Attach/Detach RAM Role