Huawei Cloud Python SDK

repository·master·Indexed 41 days ago

https://github.com/huaweicloud/huaweicloud-sdk-python-v3

A programmatic interface for interacting with Huawei Cloud services such as ECS and VPC. The SDK supports multiple authentication methods including AK/SK, environment variables, profile files, instance metadata, Pod Identity (CCE), and OIDC Trust Agency. It provides a builder pattern for client initialization, customizable HTTP configurations via HttpConfig, and a CredentialProviderChain for flexible authentication management. Requires Python 3.6 or later.

Tokens
58.1K
Snippets
89
Records
280
Agent score
48%

What's inside Huawei Cloud Python SDK

  1. Configure Authentication Credentials

    master

    Huawei Cloud services are categorized into Region-level and Global-level services. Choosing the correct credential class is critical:

    • Region-level services: Use BasicCredentials and must provide a project_id.
    • Global-level services (e.g., IAM, RMS, TMS): Use GlobalCredentials and must provide a domain_id.

    Supported Authentication Methods

    1. Temporary AK/SK & SecurityToken

    Used when obtaining temporary credentials via IAM (e.g., CreateTemporaryAccessKeyByToken).

    2. Permanent AK/SK

    Standard Access Key and Secret Key. Security Note: It is recommended to use IAM users with minimal permissions rather than the master account.

    3. IdpId & IdTokenFile

    Used for Federated Authentication via OpenID Connect (OIDC). Requires an idp_id and a file path to the id_token.

    from huaweicloudsdkcore.auth.credentials import BasicCredentials, GlobalCredentials
    
    # Region-level with Temporary Credentials
    basic_credentials = BasicCredentials(ak, sk, project_id).with_security_token(security_token)
    
    # Global-level with Permanent Credentials
    global_credentials = GlobalCredentials(ak, sk, domain_id)
    
    # Federated Authentication (Region-level)
    basic_cred = BasicCredentials() \
        .with_idp_id(idp_id) \
        .with_id_token_file(id_token_file) \
        .with_project_id(project_id)
  2. Create a service client

    master

    To interact with a Huawei Cloud service, use the service's client class (e.g., VpcClient) and its builder pattern. The builder allows you to configure credentials, the target region, and HTTP configurations.

    Key Builder Methods:

    • .with_credentials(credentials): Sets the authentication object.
    • .with_region(region_object): Sets the service region (e.g., using VpcRegion.value_of("cn-north-4")).
    • .with_http_config(http_config): Configures timeouts, proxies, and SSL settings.
    • .build(): Finalizes the client creation.
    from huaweicloudsdkvpc.v2 import VpcClient
    from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
    
    client = VpcClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(VpcRegion.value_of("cn-north-4")) \
        .build()
  3. Configure authentication with BasicCredentials

    master

    Authentication is handled using BasicCredentials. For security, avoid hard-coding your Access Key (AK) and Secret Key (SK) directly in your code. It is recommended to use environment variables.

    Set the following environment variables:

    • HUAWEICLOUD_SDK_AK
    • HUAWEICLOUD_SDK_SK

    You can also optionally provide a project_id. If project_id is omitted, the SDK will automatically attempt to query the IAM service to find the corresponding project ID for the specified region.

    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    
    # Recommended: Use environment variables
    credentials = BasicCredentials(os.getenv("HUAWEICLOUD_SDK_AK"), os.getenv("HUAWEICLOUD_SDK_SK"))
    
    # With project_id
    # credentials = BasicCredentials(os.getenv("HUAWEICLOUD_SDK_AK"), os.getenv("HUAWEICLOUD_SDK_SK"), project_id="{your_project_id}")
  4. How Region.value_of() resolves region IDs

    master

    The Region.value_of(region_id) method resolves a region ID using the following priority order:

    1. Environment Variables
    2. Configuration File
    3. SDK-defined Regions

    If the region cannot be found in any of these sources, a KeyError is raised.

    from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
    
    region1 = EcsRegion.value_of("cn-north-1")
    region2 = EcsRegion.value_of("cn-north-9")
  5. How the Credential Provider Chain works

    master

    The CredentialProviderChain allows you to attempt loading authentication through multiple methods in a specific order.

    When creating a service client without specifying credentials, the default order is: OIDC Trust Agency $\rightarrow$ Environment Variables $\rightarrow$ Profile $\rightarrow$ Metadata $\rightarrow$ Pod Identity

    You can also define a custom chain of providers.

    from huaweicloudsdkcore.auth.provider import CredentialProviderChain, ProfileCredentialProvider, MetadataCredentialProvider
    
    # Custom chain
    providers = [
        ProfileCredentialProvider.get_basic_credential_profile_provider(),
        MetadataCredentialProvider.get_basic_credential_metadata_provider()
    ]
    
    chain = CredentialProviderChain(providers)
    credentials = chain.get_credentials()
  6. Configure credentials for Huawei Cloud services

    master

    Authentication depends on whether the service is regional or global:

    • Regional Services: Require projectId to initialize BasicCredentials.
    • Global Services (e.g., IAM, BSS, TMS): Require domainId to initialize GlobalCredentials.

    Supported authentication methods:

    1. Temporary AK&SK: Uses ak, sk, and a security_token.
    2. Permanent AK&SK: Uses ak and sk.
    3. IdpId & IdTokenFile: Uses OpenID Connect identity provider ID and a token file path.

    Note: For versions 3.0.26-beta or later, project_id or domain_id can be acquired automatically if you provide the region ID during client initialization using .with_region().

    # Regional service with Permanent AK&SK
    basic_credentials = BasicCredentials(ak, sk, project_id)
    
    # Global service with Temporary AK&SK
    global_credentials = GlobalCredentials(ak, sk, domain_id).with_security_token(security_token)
    
    # Regional service with IdP
    basic_cred = BasicCredentials() \
        .with_idp_id(idp_id) \
        .with_id_token_file(id_token_file) \
        .with_project_id(project_id)
  7. Configure authentication using ProfileCredentialProvider

    master

    You can load authentication credentials from a configuration file. The file should contain [basic] or [global] sections.

    For IdpId/IdToken authentication, the configuration requires:

    • idp_id: Identity provider ID (required)
    • id_token_file: Path to the file containing the ID token (required)
    • project_id: Required for basic type authentication
    • domain_id: Required for global type authentication
    • iam_endpoint: Optional, defaults to https://iam.myhuaweicloud.com

    Example configuration file format:

    [basic]
    idp_id = your_idp_id
    id_token_file = /some_path/your_token_file
    project_id = your_project_id
    
    [global]
    idp_id = your_idp_id
    id_token_file = /some_path/your_token_file
    domainId = your_domain_id
    from huaweicloudsdkcore.auth.provider import ProfileCredentialProvider
    
    # basic
    basic_provider = ProfileCredentialProvider.get_basic_credential_profile_provider()
    basic_cred = basic_provider.get_credentials()
    
    # global
    global_provider = ProfileCredentialProvider.get_global_credential_profile_provider()
    global_cred = global_provider.get_credentials()
  8. Customize the User-Agent header

    master

    Since v3.1.165, the SDK automatically appends information (SDK language, Python version, platform, and a random identifier) to the User-Agent header to help services identify the client.

    To disable this automatic augmentation and use a custom User-Agent, set the user_agent property on an HttpConfig object and pass it to the client builder. It is recommended to keep the value under 50 characters using US-ASCII visible characters.

    http_config = HttpConfig.get_default_config()
    # Append custom User-Agent information to replace the default
    http_config.user_agent = "custom user agent..."
    
    client = IamClient.new_builder() \
        .with_http_config(http_config) \
        .build()
  9. Manage authentication using Environment Variables

    master

    You can avoid hard-coding credentials by using EnvCredentialProvider. The SDK looks for specific environment variables to build credentials.

    AK/SK Authentication

    VariableRequirementDescription
    HUAWEICLOUD_SDK_AKRequiredAccessKey
    HUAWEICLOUD_SDK_SKRequiredSecretKey
    HUAWEICLOUD_SDK_SECURITY_TOKENOptionalRequired for temporary AK/SK
    HUAWEICLOUD_SDK_PROJECT_IDOptionalRequired for regional services in multi-project scenarios
    HUAWEICLOUD_SDK_DOMAIN_IDOptionalRequired for global services

    IdpId/IdTokenFile Authentication

    VariableRequirementDescription
    HUAWEICLOUD_SDK_IDP_IDRequiredIdentity provider ID
    HUAWEICLOUD_SDK_ID_TOKEN_FILERequiredId token file path
    HUAWEICLOUD_SDK_PROJECT_IDOptionalRequired for basic credentials
    HUAWEICLOUD_SDK_DOMAIN_IDOptionalRequired for global credentials

    Usage Example

    from huaweicloudsdkcore.auth.provider import EnvCredentialProvider
    
    # For regional services
    basic_provider = EnvCredentialProvider.get_basic_credential_env_provider()
    basic_cred = basic_provider.get_credentials()
    
    # For global services
    global_provider = EnvCredentialProvider.get_global_credential_env_provider()
    global_cred = global_provider.get_credentials()