All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

Last Updated:Jan 26, 2024

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. Alibaba Cloud Credentials tool provides a powerful set of features that enable you to easily obtain and manage access credentials. This topic describes how to use the Credentials tool to configure various types of credentials such as the default credential, AccessKey pairs, or Security Token Service (STS) tokens. This topic also describes the order based on which the Credentials tool obtains the default credential. You can develop a thorough knowledge of configuring and managing credentials in Alibaba Cloud SDKs. This ensures that your operations on cloud resources are efficient and secure.

Background information

A credential is a set of information that is used to prove the identity of a user. When you log on to the system, you must use a valid credential to complete identity authentication. The following types of credentials are commonly used:

  1. An AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid. It consists of an AccessKey ID and an AccessKey secret.

  2. An STS token of a RAM role. An STS token is a temporary credential. You can specify a validity period and access permissions for an STS token. For more information, see What is STS?

  3. A bearer token. It is used for identity authentication and authorization.

Prerequisites

  • Python 3.0 or later is installed.

  • Alibaba Cloud SDK V2.0 is installed.

  • The in-house SDKs of services that use self-managed gateways are not installed.

Install the Credentials tool

We recommend that you use pip to install Alibaba Cloud Credentials for Python. Make sure that you have installed pip. For more information, see pip documentation.

pip install alibabacloud_credentials
  1. We recommend that you use the latest version of Alibaba Cloud Credentials for Python.

  2. For information about all released versions of Alibaba Cloud Credentials for Python, see ChangeLog.md.

Initialize a Credentials client

You can use multiple methods to initialize a Credentials client. Use the type parameter to specify a method to initialize a Credentials client.

Use the default credential provider chain

If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information about how to obtain the default credential provider chain, see the Default credential provider chain section of this topic.

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_ocr20191230.client import Client as OcrClient
from alibabacloud_ocr20191230.models import GetAsyncJobResultRequest
from alibabacloud_tea_rpc.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
# Do not specify a method to initialize a Credentials client.
cred = CredClient()
config = Config(credential=cred)
client = OcrClient(config)
request = GetAsyncJobResultRequest(
    job_id='<job_id>'
)
runtime_options = RuntimeOptions()
response = client.get_async_job_result(request, runtime_options)

Call example

You can use the default credential provider chain to automatically create access credentials and call the API operations of Alibaba Cloud services without the need to use a hard-coded AccessKey pair.

The following sample code provides an example on how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526 import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use the default credential to initialize the Credentials client. 
credentialsClient = CredClient()
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)
# Initialize the request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use an AccessKey pair

You can create an AccessKey pair that is used to call API operations for your Alibaba Cloud account or a RAM user. For more information, see Create an AccessKey pair. Then, you can use the AccessKey pair to initialize a Credentials client.

Warning

An Alibaba Cloud account has full access to all resources of the account. AccessKey pair leaks of an Alibaba Cloud account pose critical threats to the system.

Therefore, we recommend that you use an AccessKey pair of a RAM user that is granted minimum necessary permissions to initialize a Credentials client.

import os
from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='access_key',
	access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
	access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
cred_type = cred.get_type()

Call example

You can use the Credentials tool to read an AccessKey pair and call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

import os
# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import configurations for both the Credentials tool and ECS SDK.
from alibabacloud_tea_openapi.models import Config
from alibabacloud_credentials.models import Config as CreConfig
from alibabacloud_tea_util.models import RuntimeOptions

# Use an AccessKey pair to initialize the Credentials client. 
credentialsConfig = CreConfig(
    # Specify the type of the credential. 
    type='access_key',
    # Specify the AccessKey ID. 
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    # Specify the AccessKey secret. 
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
credentialClient = CredClient(credentialsConfig)

ecsConfig = Config(credential=credentialClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
// Initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use an STS token

You can call the AssumeRole operation of STS as a RAM user to obtain an STS token. You can specify the maximum validity period of the STS token. The following sample code provides an example on how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.

{
  "RequestId": "EA7A3526-F7DB-54A5-8300-9B742CFAA5EA",
  "AssumedRoleUser": {
    "Arn": "acs:ram::125499367423****:role/STStokenTestRole/STSsessionName",
    "AssumedRoleId": "35219123109646****:STSsessionName"
  },
  "Credentials": {
    "SecurityToken": "exampleToken",
    "AccessKeyId": "STS.exampleAccessKeyID",
    "AccessKeySecret": "exampleAccessKeySecret",
    "Expiration": "2023-03-26T05:26:06Z"
  }
}
import os
from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='sts',
  # Replace <ALIBABA_CLOUD_ACCESS_KEY_ID> with the temporary AccessKey ID that is obtained from the response to the AssumeRole operation. 
	access_key_id='<ALIBABA_CLOUD_ACCESS_KEY_ID>',  
  # Replace <ALIBABA_CLOUD_ACCESS_KEY_SECRET> with the temporary AccessKey secret that is obtained from the response to the AssumeRole operation. 
	access_key_secret='<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
  # Replace <ALIBABA_CLOUD_SECURITY_TOKEN> with the STS token that is obtained from the response to the AssumeRole operation. 
	security_token='<security_token>'
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Call example

You can use the Credentials tool to read an STS token and call the API operations of Alibaba Cloud services.

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

import os
# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import configurations for both the Credentials tool and ECS SDK.
from alibabacloud_tea_openapi.models import Config
from alibabacloud_credentials.models import Config as CreConfig
from alibabacloud_tea_util.models import RuntimeOptions

# Use an STS token to initialize the Credentials client. 
credentialsConfig = CreConfig(
    # Specify the type of the credential. 
    type='sts',
    # Specify the AccessKey ID. 
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    # Specify the AccessKey secret. 
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # Specify the STS token. 
    security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN')
)
credentialClient = CredClient(credentialsConfig)

ecsConfig = Config(credential=credentialClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
// Initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use an AccessKey pair and a RAM role

The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool can obtain an STS token from STS. You can also use the policy parameter to limit the permissions of the RAM role.

import os
from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='ram_role_arn',
	access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
	access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
	security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN'),
	# Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole.
	role_arn='<RoleArn>',
	# Specify the name of the role session.
	role_session_name='<RoleSessionName>',
	# Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
	policy='<Policy>',
	role_session_expiration=3600
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.client import Config as CredConfig
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import os

# Use the ARN of a RAM role to initialize a Credentials client. 
credentialsConfig = CredConfig(
    type='ram_role_arn',                                                  # # Specify the type of the credential. 
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),          # Specify the AccessKey ID. 
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),  # Specify the AccessKey secret. 
    security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN'),        # Specify the STS token.
    role_arn='<RoleArn>',                                                 # Specify the ARN of the RAM role to be assumed. Format: acs:ram::userID:role/roleName. 
    role_session_name='<RoleSessionName>',                                # Specify the name of the role session. 
    policy='<Policy>',                                                    # Optional. Specify limited permissions for the STS token. 
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig = Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint = 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient = EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request = DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options = RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response = ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use the RAM role of an ECS instance

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool automatically obtains the RAM role attached to an ECS instance and uses the metadata server of ECS to obtain an STS token. The STS token is then used to initialize a Credentials client. You can also attach a RAM role to an elastic container instance or a worker node in an Alibaba Cloud Container Service for Kubernetes (ACK) cluster.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='ecs_ram_role',
	# Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
	role_name='<RoleName>'
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.client import Config as CredConfig
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
# Use the RAM role of an ECS instance to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='ecs_ram_role',               # # Specify the type of the credential. 
    role_name='<ecs_ram_role_name>'    # Specify the name of the RAM role that is attached to the ECS instance. We recommend that you specify this parameter. 
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig=Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint= 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient=EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request=DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options=RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response=ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use the RAM role of an OIDC IdP

After you attach a RAM role to a worker node in an ACK cluster, applications in the pods on the worker node can use the metadata server to obtain an STS token the same way in which applications on ECS instances do. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is not available to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant minimum necessary permissions to an application. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS and obtains an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services.

The following environment variables are injected into the pod:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC identity provider (IdP).

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

import os

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='oidc_role_arn',
	access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
	access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
	security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN'),
	role_arn=os.environ.get('ALIBABA_CLOUD_ROLE_ARN'),
	oidc_provider_arn=os.environ.get('ALIBABA_CLOUD_OIDC_PROVIDER_ARN'),
	oidc_token_file_path=os.environ.get('ALIBABA_CLOUD_OIDC_TOKEN_FILE'),
	# Specify the name of the role session.
	role_session_name='<RoleSessionName>',
	# Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
	policy='<Policy>',
	# Specify the validity period of the session.
	role_session_expiration=3600
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.client import Config as CredConfig
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import os

# Use the RAM role of an OIDC IdP to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='oidc_role_arn',
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN'),
    role_arn=os.environ.get('ALIBABA_CLOUD_ROLE_ARN'),
    oidc_provider_arn=os.environ.get('ALIBABA_CLOUD_OIDC_PROVIDER_ARN'),
    oidc_token_file_path=os.environ.get('ALIBABA_CLOUD_OIDC_TOKEN_FILE'),
    # Specify the name of the role session.
    role_session_name='<RoleSessionName>',
    # Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}.
    policy='<Policy>',
    # Specify the validity period of the session.
    role_session_expiration=3600
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig=Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint= 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient=EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request=DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options=RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response=ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use a URI

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool uses the uniform resource identifier (URI) that you provide to obtain an STS token. The STS token is then used to initialize a Credentials client.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='credentials_uri',
	# Specify the URI of the credential, in the format of http://local_or_remote_uri/.
	credentials_uri='<local_or_remote_uri>',
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Call example

To call the API operations of Alibaba Cloud services, you can specify a local or remote URI for credentials and use the Credentials tool to obtain and automatically update an STS token based on the local or remote URI.

To call the operations of an Alibaba Cloud service, you must install dependencies for the Alibaba Cloud service. The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.client import Config as CredConfig
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# Use a URI to initialize the Credentials client. 
credentialsConfig = CredConfig(
    type='credentials_uri',  # # Specify the type of the credential. 
    credentials_uri='local_or_remote_uri',  # Specify the URI of the credential, in the format of http://local_or_remote_uri/. 
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig=Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint= 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient=EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request=DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options=RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response=ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Use a bearer token

Only Cloud Call Center allows you to use a bearer token to initialize a Credentials client.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config = Config(
	type='bearer',
	# Enter the bearer token.
	bearer_token='<BearerToken>',
)
cred = Client(config)

access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
security_token = cred.get_security_token()
cred_type = cred.get_type()

Call example

The following sample code provides an example on how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for Java.

# Import a Credentials client and create an alias for it. 
from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.client import Config as CredConfig
# Import an ECS SDK client and create an alias for it. 
from alibabacloud_ecs20140526.client import Client as EcsClient
# Initiate a request to call the DescribeRegions operation of ECS. 
from alibabacloud_ecs20140526.models import DescribeRegionsRequest
# Import the core Alibaba Cloud SDK package. 
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import os

# Use a bearer token to initialize the Credential client. 
credentialsConfig = CredConfig(
    type='bearer',  # # Specify the type of the credential. 
    bearer_token='<bearer_token>',  # Specify the bearer token generated by the server. The bearer token has a validity period. 
)
credentialsClient = CredClient(credentialsConfig)
ecsConfig=Config(credential=credentialsClient)
# Specify the endpoint of ECS. 
ecsConfig.endpoint= 'ecs.aliyuncs.com'
# Use the Credentials client to initialize the ECS SDK client. 
ecsClient=EcsClient(ecsConfig)

# Initialize the request to call the DescribeRegions operation. 
request=DescribeRegionsRequest()
# Initialize the runtime configurations. 
runtime_options=RuntimeOptions()
# Call the DescribeRegions operation and obtain a response. 
response=ecsClient.describe_regions_with_options(request, runtime_options)
print(response.to_map())

Default credential provider chain

If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use cred = CredClient() to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:

1. Obtain the credential information from environment variables

The Credentials tool first obtains the credential information from environment variables. If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.

2. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables:

ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.

ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

If the preceding three environment variables are specified, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.

3. Obtain the credential information from a configuration file

If no credentials are found in the previous step, the Credentials tool obtains the credential information from a configuration file. The path of the configuration file varies based on the operating system:

Linux: ~/.alibabacloud/credentials.ini

Windows: C:\Users\USER_NAME\.alibabacloud\credentials.ini

You can also specify the configuration file path by configuring the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable. If the configuration file exists, the application initializes a Credentials client by using the credential information that is specified by default in the configuration file. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to modify the default credential information that is read.

[default]
enable = true
type = access_key
access_key_id = foo
access_key_secret = bar

[client1]
type = ecs_ram_role
role_name = EcsRamRoleTest

[client2]
enable = false 
type = ram_role_arn 
region_id = cn-test 
policy = test
access_key_id = foo
access_key_secret = bar
role_arn = role_arn
role_session_name = session_name 

[client3]
type = rsa_key_pair
public_key_id = publicKeyId 
private_key_file = /your/pk.pem 

[client4] 
enable = false
type = oidc_role_arn
region_id = cn-test
policy = test
access_key_id = foo
access_key_secret = bar
role_arn = role_arn
oidc_provider_arn = oidc_provider_arn
oidc_token_file_path = /xxx/xxx
role_session_name = session_name

4. Obtain the credential information by using the RAM role of an ECS instance

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS.

5. Obtain the credential information based on a URI

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If the environment variable is specified, the application sets the value as the URI based on which the Credentials tool obtains a temporary security credential.

How to protect credential information

Credential leaks may expose the system to attacks. This is one of the main threats to cloud services. To prevent the leaks of plaintext credential information and reduce security risks, you can use the following solutions:

  1. We recommend that you use the RAM role of an ECS instance or an STS token.

  2. We recommend that you use the default credential provider chain and record the credential information in environment variables or a configuration file.

  3. To use an explicit initialization method to initialize a Credentials client, we recommend that you use system properties or environment variables to record the credential information and obtain the credential information by using the os.getenv and os.environ.get methods.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config
import os

config = Config(
	type='access_key',
	access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
	access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
)
cred = Client(config)
access_key_id = cred.get_access_key_id()
access_key_secret = cred.get_access_key_secret()
cred_type = cred.get_type()

How to switch between credentials

You can use the following methods to use different credentials to call different API operations in your application.

Use multiple Credentials clients

Initialize multiple Credentials clients to pass different credentials to different request clients.

from alibabacloud_credentials.client import Client
from alibabacloud_credentials.models import Config

config1 = Config(
	type='access_key',
	access_key_id='<ALIBABA_CLOUD_ACCESS_KEY_ID>',
	access_key_secret='<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
)
cred1 = Client(config1)

config2 = Config(
	type='access_key',
	access_key_id='<ALIBABA_CLOUD_ACCESS_KEY_ID>',
	access_key_secret='<ALIBABA_CLOUD_ACCESS_KEY_SECRET>',
)
cred2 = Client(config2)

Use the AuthUtils class

If you initialize a Credentials client by using the credential information recorded in a configuration file, you can use the auth_util.client_type parameter to switch between different credentials.

[default]
enable=true
type=access_key
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>

[client1]
enable=true
type=sts
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
security_token=<security_token>

[client2]
enable=true
type=ecs_ram_role
role_name=<ecs_ram_role_name>

Sample code:

from alibabacloud_credentials.utils import auth_util
from alibabacloud_credentials.client import Client

# If you do not specify the clientType property of the AuthUtils class, default is used. 
credentialClient = Client()
# Switch to the client1 credential.
auth_util.client_type="client1"
credentialClient1 = Client()
# Switch to the client2 credential.
auth_util.client_type="client2"
credentialClient2 = Client()

References