Todos os produtos
Search
Central de documentação

Object Storage Service:Configurar grupos de recursos

Última atualização: Jul 03, 2026

Use o OSS SDK for Python para configurar o grupo de recursos de um bucket do Object Storage Service (OSS) e consultar o ID desse grupo.

Observações

  • Os códigos de exemplo deste tópico usam, por padrão, o ID de região cn-hangzhou para a região China (Hangzhou) e um endpoint público. Para acessar o bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações, consulte Regiões e endpoints do OSS.

  • A configuração de um grupo de recursos em um bucket exige a permissão oss:PutBucketResourceGroup. A consulta do ID do grupo de recursos ao qual um bucket pertence exige a permissão oss:GetBucketResourceGroup. Para mais detalhes, consulte Conceder uma política personalizada.

Códigos de exemplo

Configurar o grupo de recursos ao qual um bucket pertence

Importante

Se você não especificar um ID de grupo de recursos ao configurar o grupo de um bucket, ele será atribuído ao grupo de recursos padrão. Certifique-se de que o grupo de recursos de destino exista antes de continuar. Para mais informações, consulte Criar um grupo de recursos.

O código de exemplo a seguir demonstra como configurar um grupo de recursos para um bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the purpose of the script: configure the resource group for a bucket.
parser = argparse.ArgumentParser(description="put bucket resource group sample")

# Define the command-line arguments, including the required parameters - region and bucket name - as well as the optional parameters - endpoint and resource group ID.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--resource_group_id',
                    help='The ID of the resource group to which the bucket belongs. (Optional, default is an empty string)',
                    default='')

def main():
    # Parse command line arguments to obtain the values entered.
    args = parser.parse_args()

    # Load access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Send a request to configure the resource group for the specified bucket.
    result = client.put_bucket_resource_group(oss.PutBucketResourceGroupRequest(
            bucket=args.bucket,  # Name of the bucket.
            bucket_resource_group_configuration=oss.BucketResourceGroupConfiguration(
                resource_group_id=args.resource_group_id,  # Resource group ID.
            ),
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Entry point of the script. The control flow starts here.

Consultar o ID do grupo de recursos ao qual um bucket pertence

O código de exemplo a seguir demonstra como consultar o ID do grupo de recursos de um bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the purpose of the script. The example describes how to query the resource group configurations of a bucket.
parser = argparse.ArgumentParser(description="get bucket resource group sample")

# Define the command-line arguments, including the required parameters — region and bucket name — as well as the optional endpoint parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command line arguments to obtain the values specified by the user.
    args = parser.parse_args()

    # Load access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSS Client instance.
    client = oss.Client(cfg)

    # Send a request to query the resource group of the bucket.
    result = client.get_bucket_resource_group(oss.GetBucketResourceGroupRequest(
            bucket=args.bucket,  # Name of the bucket.
    ))

    # Display the HTTP status code, request ID, and resource group ID to check the request status and details of configuration.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' resource group id: {getattr(result.bucket_resource_group_configuration, "resource_group_id", "Not set")},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Entry point of the script. The control flow starts here.

Referências