All Products
Search
Document Center

Object Storage Service:Configure access credentials for OSS SDK for Python

Last Updated:Jun 12, 2024

To use Object Storage Service (OSS) SDK for Python to initiate a request, you must configure access credentials. Alibaba Cloud services use access credentials to verify identity information and access permissions. You can select different types of access credentials based on authentication and authorization requirements. This topic describes how to configure temporary access credentials, long-term access credentials, and OpenID Connect (OIDC) access credentials.

Prerequisites

OSS SDK for Python is installed. For more information, see Installation.

Types of access credentials

The following types of access credentials are supported:

  • Temporary access credentials: For scenarios that require high security, such as temporary access authorization for applications to access OSS, we recommend that you use temporary access credentials. Temporary access credentials are valid only within a specific period of time to prevent credential leaks. Temporary access credentials support fine-grained access control to prevent security risks caused by excessive permissions. For more information, see Use temporary access credentials.

  • Long-term access credentials: To ensure data security, we recommend that you do not use long-term access credentials. For scenarios that require convenience, long-term access credentials eliminate the need for multiple refreshes within an extended period of time. We recommend that you change your long-term access credentials every three months to ensure the security of your Alibaba Cloud account. When long-term access credentials are leaked or no longer used, you can delete or disable the long-term access credentials to reduce security risks. For more information, see Use long-term access credentials.

  • OIDC access credentials: If you need to deploy untrusted applications to a container cluster, you may want to prevent the applications from accessing the Security Token Service (STS) token of the RAM role of the instance associated with the worker node by using a metadata service. In this case, you can use OIDC access credentials. OIDC is an authentication protocol based on OAuth 2.0. OIDC can be used to grant untrusted applications the minimal level of access. OIDC access credentials allow untrusted applications to access STS tokens safely without affecting the security of cloud resources. RAM roles support OIDC-based single sign-on (SSO). For more information, see OIDC access credentials.

Usage notes

This topic describes how to run shell commands to configure environment variables in different operating systems, such as macOS, Linux, and Windows. If you properly configure environment variables, programs started by command lines can correctly recognize the necessary configurations. If you start the programs in an integrated development environment (IDE), you may need to refer to this topic to separately configure environment variables in the IDE. This way, the programs can run as expected.

Use temporary access credentials

If you want to use OSS SDK for Python to temporarily access OSS resources, you can use one of the following methods to configure temporary access credentials:

  • Use Security Token Service (STS): If you want to access OSS within a specific period of time, you can obtain temporary access credentials from STS. The temporary access credentials obtained from STS do not disclose the AccessKey pair of your RAM user. This ensures that your access to OSS resources is secure.

  • Configure a RAM role: If you want to grant a RAM user of your Alibaba Cloud account or a RAM user of another Alibaba Cloud account the permissions to access OSS resources, you can configure a RAM role for the RAM user.

  • Configure a RAM role for an Elastic Compute Service (ECS) instance: If you want to access OSS resources from an ECS instance, you can use a RAM role of the ECS instance to access OSS resources. You can attach a RAM role to an ECS instance to access OSS resources from the instance by using temporary access credentials that are obtained from STS. STS temporary access credentials are automatically generated and updated. Applications can obtain STS temporary access credentials by using the instance metadata URL.

Use STS

  1. Create a RAM user.

    For more information, see Create a RAM user.

  2. Attach the AliyunSTSAssumeRoleAccess policy to the RAM user.

    For more information, see Grant permissions to a RAM user.

  3. Use the RAM user to call the AssumeRole operation of STS to obtain temporary access credentials.

    For more information, see AssumeRole.

  4. Configure the temporary access credentials obtained from STS.

    Specify environment variables

    1. Use the temporary access credentials obtained from STS to configure environment variables.

      macOS

      1. Open the terminal.

      2. Run the following command:

        nano ~/.bash_profile
      3. Add the temporary access credentials (AccessKeyId, AccessKeySecret, and SecurityToken) obtained from STS to the end of the file.

        export OSS_ACCESS_KEY_ID=STS.NV5ZCwphFSXqscqUHAKbH****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn**** 
        export OSS_SESSION_TOKEN=CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVt****
      4. Press Ctrl+X, press Y to save the file, and then press Enter to close the file.

      5. Run the following command for the changes to take effect:

        source ~/.bash_profile
      6. Run the following command to verify the configurations of the environment variables:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
        echo $OSS_SESSION_TOKEN

        Sample success response:

        STS.NV5ZCwphFSXqscqUHAKbH****
        IrVTNZNy5yQelTETg0cZML3TQn**** 
        CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVt****

      Linux

      1. Open the terminal.

      2. Run the following command:

        sudo vim /etc/profile
      3. Press i to enter the edit mode. Add the temporary access credentials (AccessKey ID, AccessKey secret, and security token) to the end of the file.

        export OSS_ACCESS_KEY_ID=STS.NV5ZCwphFSXqscqUHAKbH****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn****
        export OSS_SESSION_TOKEN=CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVt****
      4. Press Esc to exit the edit mode. Then, enter :wq and press Enter to save and close the file.

      5. Run the following command for the changes to take effect:

        source /etc/profile
      6. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
        echo $OSS_SESSION_TOKEN

        Sample success response:

        STS.NV5ZCwphFSXqscqUHAKbH****
        IrVTNZNy5yQelTETg0cZML3TQn**** 
        CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVt****

      Windows

      Use the GUI

      In this example, Windows 10 is used. You can perform the following steps to configure STS temporary access credentials by using environment variables on the GUI:

      1. On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section.

      2. Specify the environment variables. The following table describes the environment variables.

        Variable

        Example

        OSS_ACCESS_KEY_ID

        STS.NV5ZCw****

        OSS_ACCESS_KEY_SECRET

        IrVTNZNy****

        OSS_SESSION_TOKEN

        CAES+wMI****

      3. Run the following command to verify environment variable configurations:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%
        echo %OSS_SESSION_TOKEN%

        Sample success response:

        STS.NV5ZCw****
        IrVTNZNy**** 
        CAES+wMI****

      Use CMD

      1. Open the command-line interface (CLI).

      2. Run the following command to configure environment variables by using the temporary access credentials (AccessKey ID, AccessKey secret, and security token):

        set OSS_ACCESS_KEY_ID=STS.NV5ZCw****
        set OSS_ACCESS_KEY_SECRET=IrVTNZNy****
        set OSS_SESSION_TOKEN=CAES+wMI****
      3. Run the following command for the changes to take effect:

        setx OSS_ACCESS_KEY_ID "%OSS_ACCESS_KEY_ID%"
        setx OSS_ACCESS_KEY_SECRET "%OSS_ACCESS_KEY_SECRET%"
        setx OSS_SESSION_TOKEN "%OSS_SESSION_TOKEN%"
      4. Run the following command to verify environment variable configurations:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%
        echo %OSS_SESSION_TOKEN%

        Sample success response:

        STS.NV5ZCw****
        IrVTNZNy**** 
        CAES+wMI****

      Use Windows PowerShell

      1. Press Win+X.

      2. Specify STS temporary access credentials.

        Valid for the current session
        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for the current session:

          $env:OSS_ACCESS_KEY_ID = "STS.NV5ZCw****"
          $env:OSS_ACCESS_KEY_SECRET = "IrVTNZNy****"
          $env:OSS_SESSION_TOKEN = "CAES+wMI****"
        Valid for all new sessions
        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for all new sessions:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'STS.NV5ZCw****', [System.EnvironmentVariableTarget]::User)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::User)
          [System.Environment]::SetEnvironmentVariable('OSS_SESSION_TOKEN', 'CAES+wMI****', [System.EnvironmentVariableTarget]::User)
        Valid for all users
        1. In the message that appears, select Windows PowerShell (Administrator).

        2. Specify the following environment variables for all users:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'STS.NV5ZCw****', [System.EnvironmentVariableTarget]::Machine)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::Machine)
          [System.Environment]::SetEnvironmentVariable('OSS_SESSION_TOKEN', 'CAES+wMI****', [System.EnvironmentVariableTarget]::Machine)
      3. Run the following command to verify environment variable configurations:

        Get-ChildItem env:OSS_ACCESS_KEY_ID
        Get-ChildItem env:OSS_ACCESS_KEY_SECRET
        Get-ChildItem env:OSS_SESSION_TOKEN

        Sample success response:

        STS.NV5ZCw****
        IrVTNZNy**** 
        CAES+wMI****
    2. Obtain the temporary access credentials obtained from STS from the environment variables.

      # -*- coding: utf-8 -*-
      import oss2
      from oss2.credentials import EnvironmentVariableCredentialsProvider
      
      # Use the temporary AccessKey pair and security token that are obtained from the environment variables. 
      auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
      

    Embed access credentials in code

    Warning

    Security issues may occur if you embed access credentials in code. Leaked access credentials can be used by attackers to access your resources, which causes data breaches. To ensure security, we recommend that you use more secure methods, such as obtaining access credentials from environment variables.

    # -*- coding: utf-8 -*-
    import oss2
    
    # Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
    sts_access_key_id = 'OSS_ACCESS_KEY_ID'
    sts_access_key_secret = 'OSS_ACCESS_KEY_SECRET'
    # Specify the security token obtained from STS. 
    security_token = 'OSS_SESSION_TOKEN'
    # Initialize the StsAuth instance based on the authentication information in the temporary access credentials. 
    auth = oss2.StsAuth(sts_access_key_id,
                        sts_access_key_secret,
                        security_token)
    

Configure a RAM role for a RAM user

  1. Run the following command to install alibabacloud_credentials:

    pip install alibabacloud_credentials
  2. Obtain the AccessKey pair of a RAM user.

    For more information, see Create an AccessKey pair for a RAM user.

    Important

    To reduce the leakage risk of the AccessKey pair of a RAM user, we recommend that you rotate the AccessKey pair every three months. We recommend that you disable and delete the AccessKey pair of a RAM user that is not used for a long period of time.

  3. Obtain the RamRoleArn of the RAM role.

    Note

    RamRoleArn is the Alibaba Cloud Resource Name (ARN) of the RAM role, which is the ID of the role to be assumed. Format: acs:ram::$accountID:role/$roleName. $accountID: the ID of the Alibaba Cloud account. $roleName: the name of the RAM role.

    For more information, see View the information about a RAM role.

  4. Specify the AccessKey pair of the RAM user and the ARN of the RAM role as the temporary access credentials.

    Specify environment variables

    1. Configure environment variables for the AccessKey pair of the RAM user and the ARN of the RAM role.

      macOS

      1. Open the terminal.

      2. Run the following command:

        nano ~/.bash_profile
      3. Add the AccessKey pair of the RAM user and the ARN of the RAM role to the end of the file.

        export OSS_ACCESS_KEY_ID=LTAI4GDty8ab9W4Y1D****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn****  
        export OSS_STS_ROLE_ARN=acs:ram::17464958********:role/ossststest
      4. Press Ctrl+X, press Y to save the file, and then press Enter to close the file.

      5. Run the following command for the changes to take effect:

        source /etc/profile
      6. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
        echo $OSS_STS_ROLE_ARN

        Sample success response:

        LTAI4GDty8ab9W4Y1D****
        IrVTNZNy5yQelTETg0cZML3TQn****  
        acs:ram::17464958********:role/ossststest

      Linux

      1. Open the terminal.

      2. Run the following command:

        sudo vim /etc/profile
      3. Press i to enter the edit mode. Add the AccessKey pair of the RAM user and ARN of the RAM role to the end of the file.

        export OSS_ACCESS_KEY_ID=LTAI4GDty8ab9W4Y1D****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn****  
        export OSS_STS_ROLE_ARN=acs:ram::17464958********:role/ossststest
      4. Press Esc to exit the edit mode. Then, enter :wq and press Enter to save and close the file.

      5. Run the following command for the changes to take effect:

        source /etc/profile
      6. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
        echo $OSS_STS_ROLE_ARN

        Sample success response:

        LTAI4GDty8ab9W4Y1D****
        IrVTNZNy5yQelTETg0cZML3TQn****  
        acs:ram::17464958********:role/ossststest

      Windows

      Use the GUI

      In this example, Windows 10 is used. You can perform the following steps to configure the AccessKey pair of the RAM user and the ARN of the RAM role by using environment variables on the GUI:

      1. On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section.

      2. Specify the environment variables. The following table describes the environment variables.

        Variable

        Example

        OSS_ACCESS_KEY_ID

        LTAI****

        OSS_ACCESS_KEY_SECRET

        IrVTNZNy****

        OSS_STS_ROLE_ARN

        acs:ram::17464958********:role/ossststest

      3. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
        echo $OSS_STS_ROLE_ARN

        Sample success response:

        LTAI****
        IrVTNZNy**** 
        acs:ram::17464958********:role/ossststest

      Use CMD

      1. Open the CLI.

      2. Run the following command to configure environment variables by using the AccessKey pair of the RAM user and the ARN of the RAM role:

        set OSS_ACCESS_KEY_ID=LTAI****
        set OSS_ACCESS_KEY_SECRET=IrVTNZNy****  
        set OSS_STS_ROLE_ARN=acs:ram::17464958********:role/ossststest
      3. Run the following command for the changes to take effect:

        setx OSS_ACCESS_KEY_ID "%OSS_ACCESS_KEY_ID%"
        setx OSS_ACCESS_KEY_SECRET "%OSS_ACCESS_KEY_SECRET%"
        setx OSS_STS_ROLE_ARN "%OSS_STS_ROLE_ARN%"
      4. Run the following command to verify environment variable configurations:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%
        echo %OSS_STS_ROLE_ARN%

        Sample success response:

        LTAI****
        IrVTNZNy****  
        acs:ram::17464958********:role/ossststest

      Use Windows PowerShell

      1. Press Win+X.

      2. Specify the AccessKey pair of the RAM user and the ARN of the RAM role.

        Valid for the current session

        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for the current session:

          $env:OSS_ACCESS_KEY_ID = "LTAI****"
          $env:OSS_ACCESS_KEY_SECRET = "IrVTNZNy****"
          $env:OSS_STS_ROLE_ARN = "acs:ram::17464958********:role/ossststest"

        Valid for all new sessions

        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for all new sessions:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'LTAI****', [System.EnvironmentVariableTarget]::User)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::User)
          [System.Environment]::SetEnvironmentVariable('OSS_STS_ROLE_ARN', 'acs:ram::17464958********:role/ossststest', [System.EnvironmentVariableTarget]::User)

        Valid for all users

        1. In the message that appears, select Windows PowerShell (Administrator).

        2. Specify the following environment variables for all users:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'LTAI****', [System.EnvironmentVariableTarget]::Machine)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::Machine)
          [System.Environment]::SetEnvironmentVariable('OSS_STS_ROLE_ARN', 'acs:ram::17464958********:role/ossststest', [System.EnvironmentVariableTarget]::Machine)
      3. Run the following command to verify environment variable configurations:

        Get-ChildItem env:OSS_ACCESS_KEY_ID
        Get-ChildItem env:OSS_ACCESS_KEY_SECRET
        Get-ChildItem env:OSS_STS_ROLE_ARN

        Sample success response:

        LTAI****
        IrVTNZNy**** 
        acs:ram::17464958********:role/ossststest
    2. Obtain the AccessKey pair of the RAM user and the ARN of the RAM role from the environment variables.

      # -*- coding: utf-8 -*-
      import oss2
      from alibabacloud_credentials.client import Client
      from alibabacloud_credentials.models import Config
      from oss2 import CredentialsProvider
      from oss2.credentials import Credentials
      import os
      
      
      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)
      
      
      config = Config(
          type='ram_role_arn',
          # Obtain the AccessKey pair of the RAM user from the environment variables. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
          access_key_id=os.getenv('OSS_ACCESS_KEY_ID'),
          access_key_secret=os.getenv('OSS_ACCESS_KEY_SECRET'),
          # Obtain the ARN of the RAM role from the environment variable. 
          role_arn=os.getenv('OSS_STS_ROLE_ARN'),
          # Specify the session name of the RAM role. 
          role_session_name='roleSessionName'
      )
      
      cred = Client(config)
      
      credentials_provider = CredentialProviderWarpper(cred)
      
      # Configure access credentials by using the AccessKey pair of the RAM user and ARN of the RAM role obtained from environment variables. 
      auth = oss2.ProviderAuth(credentials_provider)
      

    Embed access credentials in code

    Warning

    Security issues may occur if you embed access credentials in code. Leaked access credentials can be used by attackers to access your resources, which causes data breaches. To ensure security, we recommend that you use more secure methods, such as obtaining access credentials from environment variables.

    # -*- coding: utf-8 -*-
    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)
    
    
    config = Config(
        type='ram_role_arn',
        # Specify the AccessKey pair of the RAM user. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        access_key_id='OSS_ACCESS_KEY_ID',
        access_key_secret='OSS_ACCESS_KEY_SECRET',
        # Specify the ARN of the RAM role. 
        role_arn='OSS_STS_ROLE_ARN',
        # Specify the session name of the RAM role. 
        role_session_name='roleSessionName'
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWarpper(cred)
    
    # Configure access credentials by using the AccessKey pair of the RAM user and ARN of the RAM role obtained from environment variables. 
    auth = oss2.ProviderAuth(credentials_provider)
    

Configure a RAM role for an ECS instance

  1. Run the following command to install alibabacloud_credentials:

    pip install alibabacloud_credentials
  2. Attach a RAM role to an ECS instance.

    For more information, see Grant permissions to the instance RAM role.

  3. Configure temporary access credentials by using the RAM role of the ECS instance.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    
    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)
    
    
    config = Config(
        type='ecs_ram_role',      # Specify the credential type. Set the value to ecs_ram_role. 
        role_name='ECSRAMRole'    # Specify the name of the RAM role that is attached to the ECS instance. This parameter is optional. If you do not configure this parameter, the system automatically searches for a RAM role. We recommended that you configure this parameter to reduce the number of requests. 
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWarpper(cred)
    
    auth = oss2.ProviderAuth(credentials_provider)
    

Use long-term access credentials

If you want to use OSS SDK for Python to access OSS resources in an application or service for a long period of time, you can configure long-term access credentials by using the AccessKey pair of a RAM user.

Configure the AccessKey pair of a RAM user

  1. Obtain the AccessKey pair of a RAM user.

    For more information, see Create an AccessKey pair for a RAM user.

    Important

    We recommend that you rotate the AccessKey pair of a RAM user that is used for more than three months. We recommend that you disable and delete the AccessKey pair of a RAM user that is not used for a long period of time. This reduces the risk of AccessKey pair leaks.

  2. Configure the AccessKey pair of the RAM user as access credentials.

    Specify environment variables

    1. Configure environment variables.

      macOS

      1. Open the terminal.

      2. Run the following command:

        nano ~/.bash_profile
      3. Add the AccessKey pair of the RAM user to the end of the file.

        export OSS_ACCESS_KEY_ID=LTAI4GDty8ab9W4Y1D****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn**** 
      4. Press Ctrl+X, press Y to save the file, and then press Enter to close the file.

      5. Run the following command for the changes to take effect:

        source ~/.bash_profile
      6. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

        Sample success response:

        LTAI4GDty8ab9W4Y1D****
        IrVTNZNy5yQelTETg0cZML3TQn**** 

      Linux

      1. Open the terminal.

      2. Run the following command:

        sudo vim /etc/profile
      3. Press i to enter the edit mode. Add the AccessKey pair of the RAM user to the end of the file.

        export OSS_ACCESS_KEY_ID=LTAI4GDty8ab9W4Y1D****
        export OSS_ACCESS_KEY_SECRET=IrVTNZNy5yQelTETg0cZML3TQn**** 
      4. Press Esc to exit the edit mode. Then, enter :wq and press Enter to save and close the file.

      5. Run the following command for the changes to take effect:

        source /etc/profile
      6. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

        Sample success response:

        LTAI4GDty8ab9W4Y1D****
        IrVTNZNy5yQelTETg0cZML3TQn**** 

      Windows

      Use the GUI

      In this example, Windows 10 is used. You can perform the following steps to configure the AccessKey pair of the RAM user by using environment variables on the GUI:

      1. On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section.

      2. Specify the environment variables. The following table describes the environment variables.

        Variable

        Example

        OSS_ACCESS_KEY_ID

        LTAI****

        OSS_ACCESS_KEY_SECRET

        IrVTNZNy****

      3. Run the following command to verify environment variable configurations:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

        Sample success response:

        LTAI****
        IrVTNZNy**** 

      Use CMD

      1. Open the CLI.

      2. Run the following command to configure the environment variables by using the AccessKey pair:

        set OSS_ACCESS_KEY_ID=LTAI****
        set OSS_ACCESS_KEY_SECRET=IrVTNZNy****  
      3. Run the following command for the changes to take effect:

        setx OSS_ACCESS_KEY_ID "%OSS_ACCESS_KEY_ID%"
        setx OSS_ACCESS_KEY_SECRET "%OSS_ACCESS_KEY_SECRET%"
      4. Run the following command to verify environment variable configurations:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

        Sample success response:

        LTAI****
        IrVTNZNy****  

      Use Windows PowerShell

      1. Press Win+X.

      2. Specify the AccessKey pair of the RAM user.

        Valid for the current session
        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for the current session:

          $env:OSS_ACCESS_KEY_ID = "LTAI****"
          $env:OSS_ACCESS_KEY_SECRET = "IrVTNZNy****"
        Valid for all new sessions
        1. In the message that appears, select Windows PowerShell.

        2. Specify the following environment variables for all new sessions:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'LTAI****', [System.EnvironmentVariableTarget]::User)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::User)
        Valid for all users
        1. In the message that appears, select Windows PowerShell (Administrator).

        2. Specify the following environment variables for all users:

          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'LTAI****', [System.EnvironmentVariableTarget]::Machine)
          [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'IrVTNZNy****', [System.EnvironmentVariableTarget]::Machine)
      3. Run the following command to verify environment variable configurations:

        Get-ChildItem env:OSS_ACCESS_KEY_ID
        Get-ChildItem env:OSS_ACCESS_KEY_SECRET

        Sample success response:

        LTAI****
        IrVTNZNy**** 
    2. Obtain the AccessKey pair of the RAM user from the environment variables.

      # -*- coding: utf-8 -*-
      import oss2
      from oss2.credentials import EnvironmentVariableCredentialsProvider
      
      # Obtain the access credentials from the environment variables. 
      auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
      

    Embed access credentials in code

    Warning

    Security issues may occur if you embed access credentials in code. Leaked access credentials can be used by attackers to access your resources, which causes data breaches. To ensure security, we recommend that you use more secure methods, such as obtaining access credentials from environment variables.

    # -*- coding: utf-8 -*-
    import oss2
    
    # Specify the AccessKey pair of the RAM user. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
    accessKeyId = 'yourAccessKeyId'
    accessKeySecret = 'yourAccessKeySecret'
    # Configure access credentials by using the embedded AccessKey pair of the RAM user. 
    auth = oss2.Auth(accessKeyId, accessKeySecret)
    

OIDC access credentials

For more information about OIDC role-based SSO, see Overview of OIDC-based SSO.

If you want to use OIDC access credentials for your application or service to access OSS, use the following steps to configure OIDC access credentials first.

  1. Run the following command to install alibabacloud_credentials:

    pip install alibabacloud_credentials
  1. Create an OIDC IdP and a RAM role for the OIDC IdP. For more information, see Create a RAM role for an OIDC IdP and Grant permissions to a RAM role.

  2. Use the RAM role to provide access credentials. The following sample code provides an example on how to create an OSSClient instance that can be used to access OSS by using OIDC access credentials:

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    
    class OIDCRoleArnCredentialDemo(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)
    
    
    config = Config(
        # Specify the credential type. Set the credential type to oidc_role_arn. 
        type='oidc_role_arn',
        # 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 security token. 
        security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN'),
        # Specify the ARN of the RAM role to assume. 
        role_arn=os.environ.get('ALIBABA_CLOUD_ROLE_ARN'),
        # Specify the ARN of the OIDC IdP. 
        oidc_provider_arn=os.environ.get('ALIBABA_CLOUD_OIDC_PROVIDER_ARN'),
        # Specify the path of the file that contains the OIDC token. 
        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)
    
    credentials_provider = OIDCRoleArnCredentialDemo(cred)
    auth = oss2.ProviderAuth(credentials_provider)
    

What to do next

After you configure the access credentials, you can initialize an OSSClient instance. For more information, see Initialization.