Todos os produtos
Search
Central de documentação

Object Storage Service:Usar o inventário de bucket

Última atualização: Jul 03, 2026

O recurso de inventário de bucket verifica periodicamente um bucket e gera arquivos CSV com metadados dos objetos, como tamanho e classe de armazenamento. Utilize esse recurso quando listar objetos individualmente pela API ListObjects for muito lento ou custoso.

Limites

  • O inventário de bucket está disponível apenas para buckets em uma região específica.

  • Para usar o recurso de inventário incremental, entre em contato com o technical support.

Casos de uso

O OSS fornece inventários completos e incrementais. Um inventário completo captura um snapshot de todos os objetos em um determinado momento; um inventário incremental captura objetos adicionados ou modificados dentro de uma janela de tempo. Inventários completos são gerados diária ou semanalmente; inventários incrementais são gerados aproximadamente a cada 10 minutos. Os casos de uso incluem:

  • Análise única de dados: configure uma regra de inventário completo para gerar um snapshot completo de metadados para análise offline.

  • Análise contínua de dados: combine inventários completos e incrementais para criar uma tabela unificada de metadados. Grave os metadados dos objetos em sua própria tabela e consulte-os com seu cluster Spark ou mecanismo de análise.

Como funciona

  • Inventário completo: gera um snapshot completo de todos os objetos no bucket, diária ou semanalmente.

    • Obter permissões: o OSS assume uma função do RAM pré-autorizada para verificar o bucket de origem e gravar o relatório no bucket de destino.

    • Verificar objetos: o OSS verifica todos os objetos correspondentes com base nos critérios de filtro da regra de inventário (prefixo, status da versão, hora de criação ou tamanho).

    • Gerar relatório de inventário: o OSS agrega os resultados da verificação e grava um arquivo CSV compactado com Gzip no bucket de destino.

  • Inventário incremental: gerado aproximadamente a cada 10 minutos, capturando eventos de alteração de objetos (criações, atualizações de metadados e exclusões).

    • Obter permissões: o OSS assume uma função do RAM pré-autorizada para verificar os logs do bucket de origem e gravar o relatório no bucket de destino.

    • Verificar objetos: o OSS verifica os logs incrementais com base nos critérios de filtro da regra de inventário (prefixo).

    • Gerar relatório de inventário: o OSS agrega os resultados da verificação por partições de backend e grava um arquivo CSV no bucket de destino.

A geração de inventário é executada de forma assíncrona e não afeta o acesso normal ao bucket.

Criar uma função de serviço

O inventário do OSS usa uma função do RAM para ler do bucket de origem e gravar no bucket de destino. Crie uma função de serviço dedicada seguindo o princípio do menor privilégio.

Ao configurar o inventário pelo console, o sistema cria automaticamente uma função chamada AliyunOSSRole. Você pode usar essa função padrão sem precisar criar uma. No entanto, essa função tem permissões totais de gerenciamento para todos os buckets da sua conta. Não use a AliyunOSSRole em produção.

Para criar manualmente uma função com menor privilégio, siga estas etapas:

(Opcional) Conceder permissão a um usuário do RAM para configurar o inventário

Uma conta Alibaba Cloud tem permissões totais por padrão e você pode pular esta etapa.

Esta etapa concede a um usuário do RAM (por exemplo, um administrador de O&M) permissão para configurar uma regra de inventário, não permissão para o próprio recurso de inventário do OSS. Uma conta Alibaba Cloud ou um administrador com altos privilégios deve criar a função do RAM antecipadamente. Um usuário padrão do RAM precisa apenas de permissão para usar a função, não para criá-la.

Para conceder a um usuário do RAM permissão para criar e gerenciar regras de inventário, conceda ao usuário uma política personalizada com as seguintes permissões:

A permissão oss:ListBuckets na política a seguir é necessária apenas ao usar o console. Se você usar um SDK ou ferramentas como ossutil, essa permissão não será necessária.
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "oss:PutBucketInventory",
                "oss:GetBucketInventory",
                "oss:DeleteBucketInventory",
                "oss:ListBuckets",
                "ram:CreateRole",
                "ram:AttachPolicyToRole",
                "ram:GetRole",
                "ram:ListPoliciesForRole"
            ],
            "Resource": "*"
        }
    ],
    "Version": "1"
}

Dica: se o usuário atual do RAM já tiver a política de sistema AliyunOSSFullAccess, você só precisará conceder permissões adicionais de gerenciamento de funções:

{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ram:CreateRole",
                "ram:AttachPolicyToRole",
                "ram:GetRole",
                "ram:ListPoliciesForRole"
            ],
            "Resource": "*"
        }
    ],
    "Version": "1"
}
  1. Criar uma função do RAM: acesse a página Criar função do RAM. Para Tipo de entidade confiável, selecione Serviço de nuvem. Para Serviço confiável, selecione OSS.

  2. Conceder à função do RAM permissão para gravar no bucket de destino:

    1. Na página Criar política, clique na aba Editor de script. Cole a seguinte política no editor de políticas e substitua dest-bucket pelo nome do seu bucket de destino.

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "oss:PutObject",
            "Resource": [
              "acs:oss:*:*:dest-bucket/*" 
            ]
          }
        ]
      }
    2. (Opcional) Configurar permissões de criptografia do KMS: se o relatório de inventário precisar ser criptografado com uma chave do KMS, você também precisará conceder à função do RAM a permissão AliyunKMSCryptoUserAccess ou permissões mais granulares relacionadas ao KMS.

    3. Na página Autorizar, clique em Adicionar permissões. Para Principal, selecione a função do RAM que você criou. Para Política de permissão, selecione a política que você acabou de criar. Em seguida, clique em Confirmar autorização.

  3. Registrar o ARN da função: na página Funções, localize a função do RAM que você criou. Acesse a página de Informações básicas e copie o ARN da função. Você precisará do ARN da função para criar uma regra de inventário. O ARN tem o formato acs:ram::{AccountID}:role/{RoleName}.

Inventário completo

Um inventário completo verifica todos os objetos no bucket ou sob um prefixo especificado. Observação:

  • Um relatório de inventário é um snapshot obtido quando a verificação começa. Alterações feitas durante a verificação podem não ser refletidas.

  • O primeiro relatório é gerado imediatamente. Os relatórios subsequentes são gerados diária ou semanalmente em lotes de madrugada (UTC+8). A latência depende da quantidade de objetos e da profundidade da fila de tarefas.

Regras de inventário

Console

  1. Faça login no Console de Gerenciamento do OSS.

  2. Navegue até o bucket de origem onde você deseja gerar um inventário. No painel de navegação à esquerda, escolha Gerenciamento de dados > Inventário de bucket.

  3. On the Bucket Inventory page, click Create Inventory.

  4. In the Create Inventory panel, configure os seguintes parâmetros:

    Parâmetro

    Descrição

    Status

    Defina o status da configuração de inventário. Selecione Start.

    Rule Name

    Insira um ID exclusivo para a configuração de inventário. O ID deve conter apenas letras minúsculas, dígitos e hifens (-) e não deve começar ou terminar com um hífen (-).

    Bucket de destino

    Especifique o destino do inventário. O bucket de destino deve estar na mesma região e conta Alibaba Cloud que o bucket de origem.

    • Para salvar o inventário no prefixo exampledir1/ no bucket examplebucket, insira exampledir1/. Se o prefixo não existir, o OSS o criará automaticamente.

    • Se você deixar este campo em branco, o inventário será salvo no diretório raiz do bucket de destino.

    Importante

    Para evitar impactos nos serviços OSS-HDFS ou riscos de corrupção de dados, não defina o prefixo de destino como .dlsdata/ ao configurar um inventário para um bucket com OSS-HDFS habilitado.

    Escopo

    • Bucket inteiro: verifica todos os objetos no bucket.

    • Object Prefix: Scan only objects that have a specific prefix, such as exampledir1/.

    Encryption Method

    Selecione se deseja criptografar o arquivo de inventário.

    Frequência

    Selecione a frequência de geração do inventário. As opções são Semanal, Diário ou Exportação única. Se o bucket contiver mais de 10 bilhões de objetos, selecione Semanal para reduzir custos e carga de verificação.

    Optional Campos

    Selecione as informações do objeto a serem incluídas no inventário:

    • Metadados do sistema: Object Size, Storage Class, Last Modified Date, ETag, TransitionTime, Multipart Upload Status, Encryption Status, Object ACL, Object Type, CRC64, Last Access Time, and Last Access Timestamp.

      Nota

      Para exportar os campos Hora do último acesso e Timestamp do último acesso, você deve primeiro habilitar o rastreamento de acesso para o bucket. Caso contrário, os valores desses campos serão nulos.

    • Metadados personalizados: Número de tags

    Filtragem avançada

    Importante

    As seguintes opções de filtro são suportadas apenas nas regiões China (Qingdao), China (Hohhot) e Alemanha (Frankfurt).

    To filter exported objects by size or last modified time, turn on the Filtragem avançada toggle.

    As opções de filtro suportadas são:

    • Time Range: Set a start and end time for the last modification date of the objects to be exported. The time is accurate to the second.

    • Object Size Range: Set the minimum and maximum size of the objects to be exported.

      Importante

      Os valores mínimo e máximo devem ser maiores que 0 B. O valor máximo não pode exceder 48,8 TB.

    • Storage Class: Specify which storage classes to export. You can export objects from Standard, Infrequent Access, Archive, Cold Archive, and Deep Cold Archive storage classes.

    Versões de objeto

    Se o versionamento estiver habilitado para o bucket, você poderá optar por exportar a Versão atual ou Todas as versões.

  5. Select I understand and agree to grant Alibaba Cloud OSS the permissions to access bucket resources, then click OK.

    Se o bucket contiver muitos objetos, a geração do inventário pode levar algum tempo. Para obter informações sobre como verificar se um inventário foi gerado, consulte Como verifico se um inventário foi gerado?.

SDK

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the name of the bucket in which you want to store the generated inventory lists. 
        String destBucketName ="yourDestinationBucketName";
        // Specify the account ID granted by the bucket owner. 
        String accountId ="yourDestinationBucketAccountId";
        // Specify the name of the RAM role that is granted the permissions to read all objects in the bucket for which you want to configure the inventory and the permissions to write data to the bucket in which you want to store the generated inventory lists. 
        String roleArn ="yourDestinationBucketRoleArn";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSS Client instance. 
        // Call the shutdown method to release associated resources when the OSS Client is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create an inventory. 
            InventoryConfiguration inventoryConfiguration = new InventoryConfiguration();

            // Specify the inventory name. 
            String inventoryId = "testid";
            inventoryConfiguration.setInventoryId(inventoryId);

            // Specify the object attributes that are included in inventory lists. 
            List<String> fields = new ArrayList<String>();
            fields.add(InventoryOptionalCampos.Size);
            fields.add(InventoryOptionalCampos.LastModifiedDate);
            fields.add(InventoryOptionalCampos.IsMultipartUploaded);
            fields.add(InventoryOptionalCampos.StorageClass);
            fields.add(InventoryOptionalCampos.ETag);
            fields.add(InventoryOptionalCampos.EncryptionStatus);
            inventoryConfiguration.setOptionalCampos(fields);

            // Specify whether to generate inventory lists on a daily or weekly basis. The following code provides an example on how to generate the inventory lists on a weekly basis. Weekly indicates that the inventory lists are generated once a week and Daily indicates that the inventory lists are generated once a day. 
            inventoryConfiguration.setSchedule(new InventorySchedule().withFrequência(InventoryFrequência.Weekly));

            // Specify that the inventory lists include only the current version of objects. If you set the InventoryIncludedObjectVersions parameter to All, all versions of objects are included in the inventory lists. This configuration takes effect only when you enable versioning for the bucket. 
            inventoryConfiguration.setIncludedObjectVersions(InventoryIncludedObjectVersions.Current);

            // Specify whether the inventory is enabled. Valid values: true and false. Set the value to true to enable the inventory. Set the value to false to disable the inventory. 
            inventoryConfiguration.setEnabled(true);

            // Specify the rule used to filter the objects to include in the inventory lists. The following code provides an example on how to filter the objects by prefix. 
            InventoryFilter inventoryFilter = new InventoryFilter().withPrefix("obj-prefix");
            inventoryConfiguration.setInventoryFilter(inventoryFilter);

            // Specify the destination bucket in which you want to store the generated inventory lists. 
            InventoryOSSBucketDestination ossInvDest = new InventoryOSSBucketDestination();
            // Specify the prefix of the path in which you want to store the generated inventory lists. 
            ossInvDest.setPrefix("destination-prefix");
            // Specify the format of the inventory lists. 
            ossInvDest.setFormat(InventoryFormat.CSV);
            // Specify the ID of the account to which the destination bucket belongs. 
            ossInvDest.setAccountId(accountId);
            // Specify the role ARN of the destination bucket. 
            ossInvDest.setRoleArn(roleArn);
            // Specify the name of the destination bucket. 
            ossInvDest.setBucket(destBucketName);

            // The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) hosted in Key Management System (KMS). 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // InventoryServerSideEncryptionKMS serverSideKmsEncryption = new InventoryServerSideEncryptionKMS().withKeyId("test-kms-id");
            // inventoryEncryption.setServerSideKmsEncryption(serverSideKmsEncryption);
            // ossInvDest.setEncryption(inventoryEncryption);

            // The following code provides an example on how to encrypt the inventory lists on the OSS server. 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // inventoryEncryption.setServerSideOssEncryption(new InventoryServerSideEncryptionOSS());
            // ossInvDest.setEncryption(inventoryEncryption);

            // Specify the destination for the generated inventory lists. 
            InventoryDestination destination = new InventoryDestination();
            destination.setOssBucketDestination(ossInvDest);
            inventoryConfiguration.setDestination(destination);

            // Configure the inventory for the bucket. 
            ossClient.setBucketInventoryConfiguration(bucketName, inventoryConfiguration);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
const OSS = require('ali-oss');

const client = new OSS({
  // The region of the bucket. For example, for China (Hangzhou), use oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this example, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // The name of the bucket.
  bucket: 'yourbucketname'
});

const inventory = {
  // The inventory ID.
  id: 'default', 
  // Specifies whether the inventory is enabled. Valid values: true and false.
  isEnabled: false, 
  // (Optional) The prefix for filtering objects.
  prefix: 'ttt',
  OSSBucketDestination: {
     // The format of the inventory.
    format: 'CSV',
   // The account ID of the destination bucket owner.
    accountId: '<Your AccountId>', 
   // The name of the role configured for the destination bucket.
    rolename: 'AliyunOSSRole',
    // The name of the destination bucket.
    bucket: '<Your BucketName>',
    // (Optional) The prefix for the destination storage path.
    prefix: '<Your Prefix>',
    // To encrypt the inventory by using SSE-OSS, use the following code.
    //encryption: {'SSE-OSS': ''},
    // To encrypt the inventory by using SSE-KMS, use the following code.
           /*
            encryption: {
      'SSE-KMS': {
        keyId: 'test-kms-id',
      }, 
    */
  },
  // The frequency at which the inventory is generated. `WEEKLY` generates a report once a week; `DAILY` generates one once a day.
  frequency: 'Daily', 
  // The object versions to include in the report. `All` includes all versions; `Current` includes only the current version.
  includedObjectVersions: 'All', 
  optionalCampos: {
    // (Optional) The optional fields to include in the inventory.
    field: ["Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus"]
  },
}

async function putInventory(){
  // The name of the bucket for which to add the inventory configuration.
  const bucket = '<Your BucketName>'; 
        try {
    await client.putBucketInventory(bucket, inventory);
    console.log('Inventory configuration added.')
  } catch(err) {
    console.log('Failed to add inventory configuration: ', err);
  }
}

putInventory()
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to create an inventory for a bucket.
parser = argparse.ArgumentParser(description="put bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, user ID, Alibaba Cloud Resource Name (ARN) of the RAM role, and inventory name.
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('--user_id', help='User account ID.', required=True)
parser.add_argument('--arn', help='The Alibaba Cloud Resource Name (ARN) of the role that has the permissions to read all objects from the source bucket and write objects to the destination bucket. Format: `acs:ram::uid:role/rolename`.', required=True)
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

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

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

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

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to create an inventory for a bucket.
    result = client.put_bucket_inventory(oss.PutBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
            inventory_configuration=oss.InventoryConfiguration(
                included_object_versions='All', # Specify that inventory lists include all versions of objects.
                optional_fields=oss.OptionalCampos(
                    fields=[ # The optional fields, such as the size and last modified time of objects.
                        oss.InventoryOptionalCampoType.SIZE,
                        oss.InventoryOptionalCampoType.LAST_MODIFIED_DATE,
                    ],
                ),
                id=args.inventory_id, # The ID of the inventory.
                is_enabled=True, # Specify whether to enable the inventory feature for the bucket. In this example, the inventory feature is enabled.
                destination=oss.InventoryDestination(
                    oss_bucket_destination=oss.InventoryOSSBucketDestination(
                        format=oss. InventoryFormatType.CSV, # Specify that the output format of the inventory lists is CSV.
                        account_id=args.user_id, # The account ID of the user.
                        role_arn=args.arn, # The ARN of the RAM role, which has the permissions to read the objects in the source bucket and write objects to the destination bucket.
                        bucket=f'acs:oss:::{args.bucket}', # The name of the destination bucket.
                        prefix='aaa', # Specify the prefix contained in the names of the objects that you want to include in inventory lists.
                    ),
                ),
                schedule=oss.InventorySchedule(
                    frequency=oss. InventoryFrequênciaType.DAILY, # Specify whether to generate inventory lists on a daily or weekly basis. In this example, inventory lists are generated on a daily basis.
                ),
                filter=oss.InventoryFilter(
                    lower_size_bound=1024, # Specify the minimum size of the object that you want to include in inventory lists. Unit: bytes.
                    upper_size_bound=1048576, # Specify the maximum size of the object that you want to include in inventory lists. Unit: bytes.
                    storage_class='ColdArchive', # # Specify the storage classes of objects that you want to include in inventory lists.
                    prefix='aaa', # Specify the prefix that is used to filter inventories.
                    last_modify_begin_time_stamp=1637883649, # Specify the beginning of the time range during which the object was last modified.
                    last_modify_end_time_stamp=1638347592, # Specify the end of the time range during which the object was last modified.
                ),
            ),
    ))

    # 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() # Specify the entry points in the functions of the script. The control program flow starts here.
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the account ID granted by the bucket owner. 
var accountId ="yourDestinationBucketAccountId";
// Specify the name of the RAM role that is granted the permissions to read all objects in the bucket for which you want to configure the inventory and the permissions to write data to the bucket in which you want to store the generated inventory lists. 
var roleArn ="yourDestinationBucketRoleArn";
// Specify the name of the bucket in which you want to store the generated inventory lists. 
var destBucketName ="yourDestinationBucketName";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Create an inventory for the bucket. 
    var config = new InventoryConfiguration();
    // Specify the name of the inventory. 
    config.Id = "report1";
    // Specify whether to enable the inventory for the bucket. Valid values: true and false. If this parameter is set to true, the inventory is enabled. 
    config.IsEnabled = true;
    // Specify the rule that is used to filter the objects included in inventory lists. The following code provides an example on how to filter the objects by prefix. 
    config.Filter = new InventoryFilter("filterPrefix");
    // Configure the bucket in which you want to store the generated inventory lists. 
    config.Destination = new InventoryDestination();
    config.Destination.OSSBucketDestination = new InventoryOSSBucketDestination();
    // Specify the format of the inventory lists. 
    config.Destination.OSSBucketDestination.Format = InventoryFormat.CSV;
    // Specify the ID of the account to which the destination bucket belongs. 
    config.Destination.OSSBucketDestination.AccountId = accountId;
    // Specify the Alibaba Cloud Resource Name (ARN) of the RAM role that is used to access the destination bucket. 
    config.Destination.OSSBucketDestination.RoleArn = roleArn;
    // Specify the name of the bucket in which you want to store the generated inventory lists. 
    config.Destination.OSSBucketDestination.Bucket = destBucketName;
    // Specify the prefix of the path in which you want to store the generated inventory lists. 
    config.Destination.OSSBucketDestination.Prefix = "prefix1";
    
    // Specify whether to generate the inventory lists on a daily or weekly basis. The following code provides an example on how to generate the inventory lists on a weekly basis. A value of Weekly indicates that the inventory lists are generated on a weekly basis. A value of Daily indicates that the inventory lists are generated on a daily basis. 
    config.Schedule = new InventorySchedule(InventoryFrequência.Daily);
    // Specify that the inventory lists include only the current versions of objects. If you set the InventoryIncludedObjectVersions parameter to All, all versions of objects are included in the inventory lists. This configuration takes effect only when versioning is enabled for the bucket. 
    config.IncludedObjectVersions = InventoryIncludedObjectVersions.All;
    
    // Specify the object attributes that are included in the inventory lists. 
    config.OptionalCampos.Add(InventoryOptionalCampo.Size);
    config.OptionalCampos.Add(InventoryOptionalCampo.LastModifiedDate);
    config.OptionalCampos.Add(InventoryOptionalCampo.StorageClass);
    config.OptionalCampos.Add(InventoryOptionalCampo.IsMultipartUploaded);
    config.OptionalCampos.Add(InventoryOptionalCampo.EncryptionStatus);
    config.OptionalCampos.Add(InventoryOptionalCampo.ETag);
    var req = new SetBucketInventoryConfigurationRequest(bucketName, config);
    client.SetBucketInventoryConfiguration(req);
    Console.WriteLine("Set bucket:{0} InventoryConfiguration succeeded", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    InventoryConfiguration inventoryConf;
    /* Specify the name of the inventory. The name must be globally unique in the current bucket. */
    inventoryConf.setId("inventoryId");

    /* Specify whether to enable inventory for the bucket. Valid values: true and false. */
    inventoryConf.setIsEnabled(true);

    /* (Optional) Specify the prefix in the names of the objects. After you specify the prefix, information about the objects whose names contain the prefix is included in the inventory lists. */
    inventoryConf.setFilter(InventoryFilter("objectPrefix"));

    InventoryOSSBucketDestination dest;
    /* Specify the format of the exported inventory lists. */
    dest.setFormat(InventoryFormat::CSV);
    /* Specify the ID of the Alibaba Cloud account to which the bucket owner grants the permissions to perform the operation. */
    dest.setAccountId("10988548********");
    /* Specify the name of the RAM role to which the bucket owner grants permissions to perform the operation. */
    dest.setRoleArn("acs:ram::10988548********:role/inventory-test");
    /* Specify the bucket in which you want to store the generated inventory lists. */
    dest.setBucket("yourDstBucketName");
    /* Specify the prefix of the path in which you want to store the generated inventory lists. */
    dest.setPrefix("yourPrefix");
    /* (Optional) Specify the method that is used to encrypt inventory lists. Valid values: SSEOSS and SSEKMS. */
    //dest.setEncryption(InventoryEncryption(InventorySSEOSS()));
    //dest.setEncryption(InventoryEncryption(InventorySSEKMS("yourKmskeyId")));
    inventoryConf.setDestination(dest);

    /* Specify the time interval at which inventory lists are exported. Valid values: Daily and Weekly. */
    inventoryConf.setSchedule(InventoryFrequência::Daily);

    /* Specify whether to include all versions of objects or only the current versions of objects in the inventory lists. Valid values: All and Current. */
    inventoryConf.setIncludedObjectVersions(InventoryIncludedObjectVersions::All);

    /* (Optional) Specify the fields that are included in inventory lists based on your requirements. */
    InventoryOptionalCampos field { 
        InventoryOptionalCampo::Size, InventoryOptionalCampo::LastModifiedDate, 
        InventoryOptionalCampo::ETag, InventoryOptionalCampo::StorageClass, 
        InventoryOptionalCampo::IsMultipartUploaded, InventoryOptionalCampo::EncryptionStatus
    };
    inventoryConf.setOptionalCampos(field);

    /* Configure the inventory. */
    auto outcome = client.SetBucketInventoryConfiguration(
        SetBucketInventoryConfigurationRequest(BucketName, inventoryConf));

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "Set Bucket Inventory fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	var (
		accountId   = "account id of the bucket" // Specify the ID of the Alibaba Cloud account to which the bucket owner grants permissions to perform the operation. Example: 109885487000****.
		inventoryId = "inventory id"             // The name of the inventory. The name must be globally unique in the bucket.
	)

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure an inventory for the bucket.
	putRequest := &oss.PutBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),  // The name of the bucket.
		InventoryId: oss.Ptr(inventoryId), // The name of the inventory specified by the user.
		InventoryConfiguration: &oss.InventoryConfiguration{
			Id:        oss.Ptr(inventoryId), // The name of the inventory specified by the user.
			IsEnabled: oss.Ptr(true),        // Enable the inventory.
			Filter: &oss.InventoryFilter{
				Prefix:                   oss.Ptr("filterPrefix"),    // Specify the rule that is used to filter the objects included in inventories.
				LastModifyBeginTimeStamp: oss.Ptr(int64(1637883649)), // The timestamp that specifies the start time of the last modification.
				LastModifyEndTimeStamp:   oss.Ptr(int64(1638347592)), // The timestamp that specifies the end time of the last modification.
				LowerSizeBound:           oss.Ptr(int64(1024)),       // The lower size limit of files (unit: bytes).
				UpperSizeBound:           oss.Ptr(int64(1048576)),    // The upper size limit of files (unit: bytes).
				StorageClass:             oss.Ptr("Standard,IA"),     // The storage class.
			},
			Destination: &oss.InventoryDestination{
				OSSBucketDestination: &oss.InventoryOSSBucketDestination{
					Format:    oss.InventoryFormatCSV,                                   // The format of the exported inventory lists.
					AccountId: oss.Ptr(accountId),                                       // Specify the ID of the account that is granted permissions by the bucket owner to perform the operation. Example: 109885487000****.
					RoleArn:   oss.Ptr("acs:ram::" + accountId + ":role/AliyunOSSRole"), // Specify the name of the RAM role that is granted permissions by the bucket owner to perform the operation. Example: acs:ram::109885487000****:role/ram-test.
					Bucket:    oss.Ptr("acs:oss:::" + bucketName),                       // Specify the name of the bucket in which you want to store the generated inventory lists.
					Prefix:    oss.Ptr("export/"),                                       // Specify the prefix of the path in which you want to store the generated inventory lists.
				},
			},
			Schedule: &oss.InventorySchedule{
				Frequência: oss.InventoryFrequênciaDaily, // The frequency at which the inventory list is exported (daily).
			},
			IncludedObjectVersions: oss.Ptr("All"), // Specify whether to include all versions of objects or only the current versions of objects in the inventory list.
		},
	}

	// Execute the request.
	putResult, err := client.PutBucketInventory(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put bucket inventory %v", err)
	}

	// Display the result.
	log.Printf("put bucket inventory result:%#v\n", putResult)
}

ossutil

Crie um arquivo chamado inventory-configuration.xml e adicione o seguinte conteúdo:

<?xml version="1.0" encoding="UTF-8"?>
<InventoryConfiguration>
  <Id>report1</Id>
    <IsEnabled>true</IsEnabled>
  <Destination>
    <OSSBucketDestination>
      <Format>CSV</Format>
      <AccountId>100000000000000</AccountId>
      <RoleArn>acs:ram::100000000000000:role/AliyunOSSRole</RoleArn>
      <Bucket>acs:oss:::destbucket</Bucket>
      <Prefix>prefix1/</Prefix>
      <Encryption>
        <SSE-KMS>
          <KeyId>keyId</KeyId>
        </SSE-KMS>
      </Encryption>
    </OSSBucketDestination>
  </Destination>
  <Schedule>
    <Frequência>Daily</Frequência>
  </Schedule>
    <IncludedObjectVersions>All</IncludedObjectVersions>
  <OptionalCampos>
    <Campo>Size</Campo>
    <Campo>LastModifiedDate</Campo>
    <Campo>ETag</Campo>
    <Campo>StorageClass</Campo>
    <Campo>IsMultipartUploaded</Campo>
    <Campo>EncryptionStatus</Campo>
  </OptionalCampos>
</InventoryConfiguration>

Execute o seguinte comando:

ossutil api put-bucket-inventory --bucket examplebucket --inventory-id report1 --inventory-configuration file://inventory-configuration.xml

Observação: para obter mais informações sobre o comando put-bucket-inventory, consulte put-bucket-inventory.

API

Chame a operação de API PutBucketInventory para configurar ou modificar uma configuração de inventário. Este método é adequado para personalização avançada, pois você deve construir manualmente a solicitação HTTP e calcular a assinatura.

Análise de inventário

As tarefas de inventário são executadas de forma assíncrona. Cada relatório de inventário é armazenado em sua própria pasta, nomeada com a hora de início da verificação. Os arquivos principais incluem manifest.json e os arquivos de dados .csv.gz no diretório data/. Para confirmar a conclusão da tarefa, verifique se o arquivo manifest.json foi gerado no destino.

  1. Analisar o arquivo manifest.json: analise o arquivo manifest.json para obter a ordem correta das colunas e as informações dos arquivos de dados, concentrando-se nos dois campos a seguir:

    • fileSchema: uma string que define os nomes das colunas e a ordem exata no arquivo de dados CSV.

    • files: um array que lista os detalhes de cada arquivo de dados .csv.gz gerado para este relatório, incluindo:

      • key: caminho do arquivo

      • size: tamanho do arquivo

      • MD5checksum: soma de verificação MD5

  2. Analisar os arquivos de dados CSV de acordo com o fileSchema

    1. Baixar e descompactar os arquivos de dados: para cada arquivo de dados no array files do manifest.json, use sua key (o caminho do arquivo) para baixar o arquivo .csv.gz correspondente. Descompacte o arquivo para obter os dados no formato CSV.

    2. Analisar os dados em ordem:

      Use a ordem dos campos do fileSchema como cabeçalhos das colunas. Leia o arquivo CSV descompactado linha por linha. Cada linha é um registro completo de um objeto, e cada coluna corresponde a um campo no fileSchema.

      Exemplo de conteúdo CSV: se o fileSchema for "Bucket,Key,Size,StorageClass,LastModifiedDate", o conteúdo CSV descompactado terá o seguinte formato:

      source-bucket,"dir%2Fbody.xml","102400","Standard","2025-04-14T07-06-00Z"
      source-bucket,"dest.png","312049","Standard","2025-04-14T07-05-59Z"
      O valor Key é codificado em URL e pode ser decodificado conforme necessário.

Arquivo de inventário completo

Após configurar uma tarefa de inventário, o OSS gera arquivos de inventário com base no período de exportação definido na regra de inventário. A estrutura de diretórios dos arquivos de inventário é a seguinte:

<dest-bucket-name>/
└── <dest-prefix>/
    └── <source-bucket-name>/
        └── <inventory-id>/
            ├── YYYY-MM-DDTHH-MMZ/  (UTC timestamp when the scan started)
            │   ├── manifest.json   (Metadata file for the inventory task)
            │   └── manifest.checksum (MD5 checksum of the manifest.json file)
            └── data/
                └── <uuid>.csv.gz   (One or more GZIP-compressed inventory data files)

Estrutura de diretórios

Descrição

dest-prefix

Este diretório é nomeado com base no prefixo especificado para o relatório de inventário. Se nenhum prefixo for especificado, este diretório será omitido.

source-bucket-name

Este diretório é nomeado com base no bucket de origem do relatório de inventário.

inventory-id

Este diretório é nomeado com base no nome da regra da tarefa de inventário.

YYYY-MM-DDTHH-MMZ

Este diretório é nomeado usando o timestamp UTC da hora de início da verificação (por exemplo, 2025-05-17T16-00Z). Ele contém os arquivos manifest.json e manifest.checksum.

data

Este diretório contém arquivos de inventário CSV compactados com GZIP. Esses arquivos listam os objetos no bucket de origem e seus metadados correspondentes.

Importante
  • Para buckets de origem com muitos objetos, o inventário é dividido automaticamente em vários arquivos CSV compactados com GZIP para simplificar o download e o processamento. Os arquivos são nomeados sequencialmente, como uuid.csv.gz, uuid-1.csv.gz e uuid-2.csv.gz. Você pode obter a lista de arquivos CSV do arquivo manifest.json e depois descompactá-los e lê-los em sequência para processar os dados do inventário.

  • O registro de um único objeto nunca é dividido em vários arquivos de inventário.

Arquivo de manifesto

O arquivo de manifesto consiste em manifest.json e manifest.checksum, conforme detalhado abaixo:

  • manifest.json: contém metadados e outras informações básicas sobre o inventário.

    {
        "creationTimestamp": "1642994594",
        "destinationBucket": "dest-bucket-name",
        "fileFormat": "CSV",
        "fileSchema": "Bucket, Key, VersionId, IsLatest, IsDeleteMarker, Size, StorageClass, LastModifiedDate, ETag, IsMultipartUploaded, EncryptionStatus, ObjectAcl, TaggingCount, ObjectType, CRC64",
        "files": [{
                "MD5checksum": "F77449179760C3B13F1E76110F07****",
                "key": "dest-prefix/source-bucket-name/inventory-id/data/a1574226-b5e5-40ee-91df-356845777c04.csv.gz",
                "size": 2046}],
        "sourceBucket": "source-bucket-name",
        "version": "2019-09-01"
    }

    A tabela a seguir descreve cada campo.

    Parâmetro

    Descrição

    creationTimestamp

    O timestamp de quando a verificação do bucket de origem começou.

    destinationBucket

    O bucket de destino que armazena os arquivos de inventário.

    fileFormat

    O formato do arquivo de inventário.

    fileSchema

    Os campos no arquivo de inventário, categorizados como fixos e opcionais. A ordem dos campos fixos é constante. A ordem dos campos opcionais depende da ordem em que você os selecionou ao configurar a regra de inventário. Para evitar incompatibilidades, analise as colunas de dados no arquivo .csv.gz de acordo com a ordem dos campos no fileSchema.

    • Se você selecionar a versão atual para a versão do objeto ao configurar uma regra de inventário, o fileSchema listará primeiro os campos fixos Bucket, Key, seguidos pelos campos opcionais.

    • Ao configurar uma regra de inventário para incluir todas as versões de objetos, o fileSchema listará primeiro os campos fixos Bucket, Key, VersionId, IsLatest, IsDeleteMarker, seguidos pelos campos opcionais.

    files

    Uma lista de arquivos de inventário. Cada entrada especifica a soma de verificação MD5, a chave e o tamanho de um arquivo.

    sourceBucket

    O bucket de origem onde a regra de inventário está configurada.

    version

    A versão do inventário.

  • manifest.checksum: o arquivo manifest.checksum contém o hash MD5 do arquivo manifest.json. Use esse hash para verificar a integridade do manifest.json. Por exemplo: F77449179760C3B13F1E76110F07****.

Inventário completo

O relatório de inventário é armazenado no diretório data/ e lista os arquivos exportados pelo recurso de inventário. Veja um exemplo a seguir:

image

Parâmetro

Descrição

bucket

O bucket de origem onde a tarefa de inventário é executada.

key

A chave do objeto.

Esta chave é codificada em URL e pode ser decodificada conforme necessário.

VersionId

O ID da versão do objeto. Este campo está presente apenas quando o inventário está configurado para incluir todas as versões dos objetos.

  • Se o versionamento estiver desabilitado para o bucket, este campo estará vazio.

  • Se o versionamento estiver habilitado para o bucket, este campo exibirá o VersionId do objeto.

IsLatest

Indica se a versão do objeto é a mais recente. Este campo está presente apenas quando o inventário está configurado para incluir todas as versões dos objetos.

  • Se o versionamento estiver desabilitado para o bucket, este campo será true.

  • Se o versionamento estiver habilitado para o bucket, este campo será true para a versão mais recente e false para versões anteriores.

IsDeleteMarker

Indica se a versão do objeto é um marcador de exclusão. Este campo está presente apenas quando o inventário está configurado para incluir todas as versões dos objetos.

  • Se o versionamento estiver desabilitado para o bucket, este campo será false.

  • Se o versionamento estiver habilitado para o bucket, este campo será true se a versão do objeto for um marcador de exclusão e false caso contrário.

size

O tamanho do objeto.

StorageClass

A classe de armazenamento do objeto.

LastModifiedDate

A hora da última modificação do objeto, no Horário Universal Coordenado (UTC), que está 8 horas atrás do Horário de Pequim.

TransitionTime

A hora em que o objeto foi transferido para a classe de armazenamento Cold Archive ou Deep Cold Archive por uma regra de ciclo de vida.

ETag

O ETag do objeto.

Um identificador para o conteúdo do objeto, gerado quando o objeto é criado.

  • Para um objeto criado com a operação PutObject, o ETag é o hash MD5 do conteúdo do objeto.

  • Para objetos criados por qualquer outro método, o ETag é um valor calculado exclusivo e não o hash MD5 do conteúdo.

IsMultipartUploaded

true se o objeto foi criado por um upload multipart; false caso contrário.

EncryptionStatus

true se o objeto estiver criptografado; false caso contrário.

ObjectAcl

A ACL do objeto. ACL do objeto.

TaggingCount

O número de tags no objeto.

ObjectType

O tipo de objeto. tipo de objeto.

CRC64

A soma de verificação CRC64 do objeto.

LastAccessDate

A hora do último acesso ao objeto, no Horário Universal Coordenado (UTC).

Nota

Este campo está disponível apenas quando o rastreamento de acesso está habilitado para o bucket. Caso contrário, este campo será nulo.

LastAccessTimestamp

A hora do último acesso ao objeto, como um timestamp Unix.

Nota

Este campo está disponível apenas quando o rastreamento de acesso está habilitado para o bucket. Caso contrário, este campo será nulo.

Inventário incremental

Um inventário incremental é executado aproximadamente a cada 10 minutos para capturar e relatar alterações nos objetos, incluindo criações, atualizações de metadados e exclusões.

Configurar uma regra de inventário

Console

  1. Faça login no console do OSS.

  2. Navegue até o bucket de origem para o qual deseja gerar um inventário. No painel de navegação à esquerda, escolha Gerenciamento de dados > Inventário de bucket.

  3. On the Bucket Inventory page, click Create Inventory.

  4. In the Create Inventory panel:

    1. Configure the Basic Settings parameters.

      Parâmetro

      Descrição

      Status

      Defina o status da tarefa de inventário incremental. Selecione Start.

      Rule Name

      Insira um nome para a tarefa de inventário. O nome pode conter apenas letras minúsculas, dígitos e hifens (-) e não pode começar ou terminar com um hífen.

      Inventory Report Destination

      Especifique o caminho de armazenamento para o relatório de inventário. O bucket de origem e o bucket de destino devem pertencer à mesma conta Alibaba Cloud e estar na mesma região.

      • Para salvar o relatório no caminho exampledir1/ no bucket examplebucket, insira exampledir1/. Se o caminho especificado não existir no bucket, o OSS o criará automaticamente. O prefixo do caminho de destino não pode exceder 128 caracteres.

      • Se você deixar este campo em branco, o relatório será salvo no diretório raiz.

      Importante

      Para evitar impactos no OSS-HDFS e possíveis corrupções de dados, não defina o diretório do relatório de inventário como .dlsdata/ ao configurar uma regra de inventário para um bucket com OSS-HDFS habilitado.

      Scan Escopo

      • Scan Entire Bucket: Scan all objects in the bucket.

      • Object Prefix: Scan only objects with a specified prefix, such as exampledir1/.

    2. In the Track and Generate Incremental Metadata Updates area, enable Get Incremental Metadata Updates, and select the Metadata Campos to export.

      Parâmetro

      Descrição

      Metadata Campos

      Selecione os metadados do objeto a serem incluídos no relatório.

      • Metadados de evento: Serial Number, Event Type, Timestamp, User ID, Request ID, and Source IP.

      • Metadados do sistema: Object Size, Storage Class, Last Modified Date, ETag, Multipart Upload Status, object type, object ACL, CRC64, and Encryption Status.

  5. Select I acknowledge and agree to grant Alibaba Cloud OSS the permissions to access bucket resources, and then click OK.

Ossutil

Crie um arquivo chamado incremental-inventory.xml. A principal diferença em relação à configuração de inventário completo é a adição da seção <IncrementalInventory>.

<?xml version="1.0" encoding="UTF-8"?>
<InventoryConfiguration>
    <Id>Report-1</Id>
    <IsEnabled>true</IsEnabled>
    <Filter>
      <Prefix>test</Prefix>
    </Filter>
    <Destination>
      <OSSBucketDestination>
        <Format>CSV</Format>
        <AccountId>12xxxxxx29</AccountId>
        <RoleArn>acs:ram::12xxxxxx29:role/AliyunOSSRole</RoleArn>
        <Bucket>acs:oss:::test-inc-bi-bj</Bucket>
        <Prefix>Report-1</Prefix>
      </OSSBucketDestination>
    </Destination>
    <Schedule>
      <Frequência>Weekly</Frequência>
    </Schedule>
    <IncludedObjectVersions>All</IncludedObjectVersions>
    <OptionalCampos>
      <Campo>Size</Campo>
      <Campo>LastModifiedDate</Campo>
      <Campo>ETag</Campo>
      <Campo>StorageClass</Campo>
    </OptionalCampos>
    <IncrementalInventory>
      <IsEnabled>true</IsEnabled>
      <Schedule>
        <Frequência>600</Frequência>
      </Schedule>
      <OptionalCampos>
        <Campo>SequenceNumber</Campo>
        <Campo>RecordType</Campo>
        <Campo>RecordTimestamp</Campo>
        <Campo>Requester</Campo>
        <Campo>RequestId</Campo>
        <Campo>SourceIp</Campo>
        <Campo>Size</Campo>
        <Campo>StorageClass</Campo>
        <Campo>LastModifiedDate</Campo>
        <Campo>ETag</Campo>
        <Campo>IsMultipartUploaded</Campo>
        <Campo>ObjectType</Campo>
        <Campo>ObjectAcl</Campo>
        <Campo>Crc64</Campo>
        <Campo>EncryptionStatus</Campo>
      </OptionalCampos>
    </IncrementalInventory>
  </InventoryConfiguration>

Execute o seguinte comando:

ossutil api put-bucket-inventory --bucket examplebucket --inventory-id report1 --inventory-configuration file://inventory-configuration.xml
Observação: para obter mais informações sobre o comando put-bucket-inventory, consulte put-bucket-inventory.

API

Chame a operação PutBucketInventory para configurar ou modificar uma configuração de inventário. Este método é adequado para cenários altamente personalizados, pois exige que você construa manualmente uma solicitação HTTP e calcule a assinatura.

Analisar um relatório de inventário

Após a conclusão de uma tarefa de inventário, o OSS gera arquivos de relatório no caminho especificado no bucket de destino. Os arquivos principais incluem:

  • Um arquivo manifest.json

  • Arquivos de dados .csv no diretório data/

Para confirmar a conclusão da tarefa, verifique se o arquivo manifest.json existe no bucket de destino.

Siga estas etapas para analisar o relatório:

  1. Ler o arquivo manifest.json: a ordem das colunas em um relatório de inventário é dinâmica e depende dos campos selecionados ao configurar a regra de inventário. Você deve primeiro analisar o campo fileSchema no arquivo manifest.json. Esse campo define o nome e a ordem de cada coluna no arquivo CSV.

  2. Analisar os arquivos de dados CSV com base no fileSchema

    • Use a ordem definida no fileSchema como cabeçalhos das colunas do arquivo CSV.

    • Leia o arquivo CSV linha por linha. Cada linha representa um registro completo de objeto, e cada coluna corresponde a um campo declarado no fileSchema.

Arquivos de inventário incremental

Após configurar uma tarefa de inventário, o OSS gera arquivos de inventário na frequência especificada na regra de inventário. A estrutura de diretórios dos arquivos de inventário é a seguinte:

<dest-bucket-name>/
└── <dest-prefix>/
    └── <source-bucket-name>/
       └── <inventory-id>/
          └── incremental_inventory/
             └── YYYY-MM-DDTHH-MMSSZ/
                 ├── manifest.json  
                 └── data/
                     ├── uuid1_0.csv
                     └── ......

Estrutura de diretórios

Descrição

dest-prefix

Este diretório é gerado com base no prefixo especificado para o relatório de inventário. Se nenhum prefixo for especificado, este diretório será omitido.

source-bucket-name

Este diretório é gerado com base no nome do bucket de origem.

inventory_id

Este diretório é nomeado com base no nome da regra de inventário.

incremental_inventory

Um prefixo fixo para o inventário incremental que o distingue de um inventário completo.

YYYY-MM-DDTHH-MMSSZ

Um timestamp UTC padrão que indica quando a verificação do bucket começou. Exemplo: 2020-05-17T16-0000Z.

data

Este diretório contém os arquivos de inventário no formato CSV. Os arquivos listam os objetos e seus metadados que foram modificados no bucket de origem dentro do período especificado.

Arquivo de manifesto

{
    "startTimestamp": "1759320000",
    "endTimestamp": "1759320600",
    "destinationBucket": "destbucket",
    "fileFormat": "CSV",
    "fileSchema": "Bucket, Key, VersionId, IsDeleteMarker, SequenceNumber, RecordType, RecordTimestamp, Requester, RequestId, SourceIp, Size, StorageClass, LastModifiedDate, ETag, IsMultipartUploaded, ObjectType, ObjectAcl, CRC64, EncryptionStatus",
    "files": [{
            "MD5checksum": "60463A9A34019CF448A730EB2CB3****",
            "key": "dest-prefix/source-bucket-name/inventory-id/incremental_inventory/2025-09-28T07-4000Z/data/5b7c6cf0db490db906c60e87b917b148_5550506986a37a62abce56a83db6736d_0.csv",
            "size": 2046}],
    "sourceBucket": "srcbucket",
    "version": "2025-09-30"
}

A tabela a seguir descreve cada campo.

Campo

Descrição

startTimestamp

O timestamp que indica o início da janela de tempo coberta por este relatório de inventário incremental.

endTimestamp

O timestamp que indica o fim da janela de tempo coberta por este relatório de inventário incremental.

destinationBucket

O bucket de destino onde os arquivos de inventário são armazenados.

fileFormat

O formato do arquivo de inventário.

fileSchema

Especifica os campos no arquivo de inventário. O esquema inclui campos fixos, que têm ordem constante, e campos opcionais, cuja ordem depende da sequência de seleção durante a configuração da regra. Para evitar incompatibilidades de colunas, sempre analise os dados CSV com base na ordem dos campos definida no fileSchema.

  • Se você selecionar Versão atual para Versão do objeto ao configurar uma regra de inventário, o fileSchema começará com os campos fixos Bucket, Key, seguidos pelos campos opcionais.

  • Se você selecionar Todas as versões para Versão do objeto ao configurar uma regra de inventário, o fileSchema começará com os campos fixos Bucket, Key, VersionId, IsDeleteMarker, seguidos pelos campos opcionais.

files

Uma lista contendo a soma de verificação MD5, a chave completa e o tamanho de cada arquivo de inventário.

sourceBucket

O bucket de origem para o qual a regra de inventário está configurada.

version

A versão do inventário.

Campos do relatório de inventário incremental

Tipo de metadados

Campo

Descrição

Metadados do sistema

Bucket

The name of the source bucket on which the inventory task runs.

Metadados de evento

Sequence number

Um número de sequência exclusivo para cada registro. Classificar registros do mesmo objeto por SequenceNumber geralmente preserva a ordem cronológica.

Record type

O tipo de registro: CREATE, UPDATE_METADATA ou DELETE.

  • CREATE: inclui todos os métodos de upload sob o prefixo selecionado, como PutObject, PostObject, AppendObject, MultipartUpload e CopyObject.

  • UPDATE_METADATA: inclui todas as atualizações de metadados para objetos sob o prefixo selecionado.

  • DELETE: inclui todos os métodos de exclusão para objetos sob o prefixo selecionado, como DeleteObject, DeleteMultipleObjects, a criação de um marcador de exclusão quando o versionamento está habilitado e exclusões baseadas em ciclo de vida. As exclusões podem ser marcadores de exclusão ou exclusões permanentes. Para uma exclusão permanente, o registro mantém apenas os campos principais Bucket, Key, SequenceNumber, RecordType, RecordTimestamp e VersionId. Todas as outras colunas ficam vazias.

Record timestamp

Um timestamp em UTC com precisão de milissegundos. Exemplo: "2024-08-25 18:08:01.024".

Requester

O ID Alibaba Cloud ou ID principal do solicitante.

Request ID

O identificador exclusivo da solicitação.

Source IP

O endereço IP de origem do solicitante.

Metadados do sistema

Key

O nome do objeto no bucket. O nome é codificado em URL.

Version ID

O ID da versão do objeto. Este campo é incluído apenas quando a regra de inventário está configurada para exportar todas as versões.

  • Se o versionamento estiver desabilitado para o bucket, este campo estará vazio.

  • Se o versionamento estiver habilitado para o bucket, este campo exibirá o VersionId do objeto.

Is delete marker

Indica se a versão do objeto é um marcador de exclusão. Este campo é incluído apenas quando a regra de inventário está configurada para exportar todas as versões.

  • Se o versionamento estiver desabilitado para o bucket, este campo assumirá o valor padrão false.

  • Se o versionamento estiver habilitado e a versão do objeto for um marcador de exclusão, este campo será true. Se a versão do objeto não for um marcador de exclusão, este campo será false.

Size

O tamanho do objeto em bytes.

Storage class

A classe de armazenamento do objeto.

Last modified date

A hora da última modificação do objeto. A hora está em UTC, que está 8 horas atrás do Horário de Pequim (UTC+8).

ETag

Uma entity tag (ETag) que identifica o conteúdo do objeto.

  • Para objetos criados usando a operação PutObject, o valor do ETag é o hash MD5 do conteúdo do objeto.

  • Para objetos criados por outros métodos, o valor do ETag é um valor exclusivo gerado com base em uma regra de cálculo específica, mas não é o hash MD5 do conteúdo do objeto.

Is multipart uploaded

Indica se o objeto foi criado por um upload multipart. Um valor true indica que sim; false indica que não.

Encryption status

Indica se o objeto está criptografado. Um valor true indica que sim; false indica que não.

Object ACL

A ACL do objeto. ACL do objeto.

Object type

O tipo do objeto. Para obter mais informações, consulte Tipos de objeto.

CRC64

O valor CRC64 do objeto.

Limites

Cada bucket suporta até 1.000 regras de inventário por API ou SDK, ou 10 pelo console.

Faturamento

O inventário de bucket em si é gratuito, mas as seguintes taxas se aplicam:

  • Taxas de solicitação de API: solicitações Put e Get para configurar ou recuperar regras de inventário. Solicitações PUT quando o OSS grava relatórios no bucket de destino. Solicitações GET quando você baixa relatórios.

  • Taxas de armazenamento: taxas de armazenamento padrão se aplicam aos relatórios de inventário (arquivos manifest e csv.gz ou csv) no bucket de destino.

  • Taxas de tráfego de saída: baixar relatórios de inventário de um endpoint público incorre em taxas de tráfego de saída.

  • Exclua regras de inventário que você não precisa mais e use regras de ciclo de vida para limpar automaticamente arquivos de relatórios expirados.

Diretrizes de produção

Práticas recomendadas

  • Menor privilégio: sempre use uma função dedicada do RAM com menor privilégio. Nunca use AliyunOSSRole em um ambiente de produção.

  • Recomendação de desempenho: para buckets de origem com alto tráfego, armazene os relatórios de inventário em um bucket separado para evitar contenção de largura de banda com serviços online.

  • Otimização de custos: para buckets com mais de dez bilhões de objetos, use exportações semanais. Configure uma regra de ciclo de vida no bucket de destino para excluir automaticamente relatórios com mais de um número especificado de dias, como 30.

    Número de objetos

    Recomendação de exportação

    <10 bilhões

    Configure exportações diárias ou semanais conforme necessário

    10 bilhões a 50 bilhões

    Exportar semanalmente

    ≥50 bilhões

    • Exportar em lotes por prefixos correspondentes

    • para aumentar o limite de exportação

  • Particionamento por prefixo: para buckets extremamente grandes (centenas de bilhões de objetos), crie várias regras de inventário com base em prefixos de negócios para gerar relatórios de forma dividida.

Prevenção de riscos

  • Auditoria de dados: um relatório de inventário pode não listar todos os objetos. O relatório inclui objetos cuja hora da última modificação é anterior ao createTimeStamp no manifest.json. Objetos modificados após esse timestamp podem ser excluídos. Antes de agir com base nos dados do inventário, verifique as propriedades atuais do objeto pela API HeadObject.

  • Monitoramento e alertas: monitore o uso de armazenamento do bucket de destino para evitar custos descontrolados. Monitore chamadas de API como PutBucketInventory para rastrear alterações de configuração.

  • Gerenciamento de alterações: alterações em uma regra de inventário (prefixo, frequência etc.) podem afetar fluxos de trabalho de análise de dados downstream. Incorpore as alterações aos seus processos de controle de versão e revisão.

Perguntas frequentes