Use o OSS Node.js SDK para adicionar, visualizar, listar e excluir configurações de inventário de um bucket.
Se você usar o recurso de inventário como usuário do RAM (Resource Access Management), verifique se tem as permissões necessárias. Para mais detalhes, consulte Classificação de ações do OSS.
Adicionar uma configuração de inventário
Antes de adicionar uma configuração de inventário, observe os seguintes limites:
Um bucket pode ter no máximo 1.000 regras de inventário.
O bucket de origem e o bucket de destino devem estar na mesma região. O bucket de origem contém os objetos a serem inventariados. O bucket de destino armazena os arquivos de manifesto do inventário gerados pelo OSS.
O código a seguir adiciona uma configuração de inventário a um bucket. Todos os exemplos usam CommonJS (require). Se o seu projeto usar módulos ES, substitua a linha require por import OSS from 'ali-oss'.
const OSS = require('ali-oss');
const client = new OSS({
// Specify the source bucket name.
bucket: 'yourBucketName',
// Specify the region where the source bucket is located, for example, oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
});
const inventory = {
id: 'default', // required — unique ID for the inventory configuration
isEnabled: false, // required — true to enable, false to disable
prefix: 'logs/', // optional — filter objects by key prefix
OSSBucketDestination: {
format: 'CSV', // required — inventory output format; only CSV is supported
accountId: 'yourAccountId', // required — Alibaba Cloud account ID of the destination bucket owner
rolename: 'AliyunOSSRole', // required — RAM role name granted write access to the destination bucket
bucket: 'yourDestBucketName', // required — destination bucket name
prefix: 'inventory-reports/', // optional — key prefix for inventory files in the destination bucket
// To encrypt inventory files with SSE-OSS:
// encryption: { 'SSE-OSS': '' }
// To encrypt with SSE-KMS:
// encryption: { 'SSE-KMS': { keyId: 'your-kms-key-id' } }
},
frequency: 'Daily', // required — 'Daily' or 'Weekly'
includedObjectVersions: 'All', // required — 'All' (all versions) or 'Current' (latest version only)
optionalFields: {
field: [ // optional — additional object attributes to include in the report
'Size',
'LastModifiedDate',
'ETag',
'StorageClass',
'IsMultipartUploaded',
'EncryptionStatus',
],
},
};
async function putInventory() {
const bucket = 'yourBucketName';
try {
await client.putBucketInventory(bucket, inventory);
console.log('Inventory configuration added.');
} catch (err) {
console.error('Failed to add inventory configuration:', err);
}
}
putInventory();
A tabela a seguir descreve os principais parâmetros:
|
Parâmetro |
Obrigatório |
Descrição |
|
|
Sim |
Identificador exclusivo da configuração de inventário. |
|
|
Sim |
Define se a configuração deve ser ativada. Use |
|
|
Não |
Filtra o inventário para objetos cujas chaves começam com este prefixo. |
|
|
Sim |
Formato de saída do arquivo de inventário. Apenas |
|
|
Sim |
ID da conta Alibaba Cloud do proprietário do bucket de destino. |
|
|
Sim |
Nome da função do RAM com acesso de gravação ao bucket de destino. |
|
|
Sim |
Nome do bucket de destino. |
|
|
Não |
Prefixo de chave para os arquivos de inventário armazenados no bucket de destino. |
|
|
Sim |
Agenda de geração. Valores válidos: |
|
|
Sim |
Versões de objeto a incluir. |
|
|
Não |
Atributos adicionais para incluir no relatório. Valores válidos: |
Visualizar uma configuração de inventário
O código a seguir recupera uma configuração de inventário pelo ID.
const OSS = require('ali-oss');
const client = new OSS({
bucket: 'yourBucketName',
region: 'yourRegion',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
});
async function getBucketInventoryById() {
const bucket = 'yourBucketName';
try {
const result = await client.getBucketInventory(bucket, 'yourInventoryId');
console.log(result.inventory);
} catch (err) {
console.error(err);
}
}
getBucketInventoryById();
Listar configurações de inventário
Uma única solicitação retorna no máximo 100 configurações de inventário. Para obter mais resultados, envie várias solicitações paginadas usando o nextContinuationToken de cada resposta.
O código a seguir lista todas as configurações de inventário de um bucket e itera pelas páginas até recuperar todos os resultados.
const OSS = require('ali-oss');
const client = new OSS({
bucket: 'yourBucketName',
region: 'yourRegion',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
});
async function listBucketInventory() {
const bucket = 'yourBucketName';
async function getNextPage(continuationToken) {
const result = await client.listBucketInventory(bucket, continuationToken);
// result shape:
// {
// inventoryList: [ { id, isEnabled, ... }, ... ],
// nextContinuationToken: 'STRING_VALUE' | undefined // undefined means no more pages
// }
console.log(result.inventoryList);
if (result.nextContinuationToken) {
await getNextPage(result.nextContinuationToken);
}
}
await getNextPage();
}
listBucketInventory();
Excluir uma configuração de inventário
O código a seguir exclui uma configuração de inventário pelo ID.
const OSS = require('ali-oss');
const client = new OSS({
bucket: 'yourBucketName',
region: 'yourRegion',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
});
async function deleteBucketInventoryById() {
const bucket = 'yourBucketName';
const inventoryId = 'yourInventoryId';
try {
await client.deleteBucketInventory(bucket, inventoryId);
console.log('Inventory configuration deleted.');
} catch (err) {
console.error('Failed to delete inventory configuration:', err);
}
}
deleteBucketInventoryById();
Referências
Para obter o código de exemplo completo, consulte Exemplos no GitHub.
Para adicionar uma configuração de inventário de bucket via API, consulte PutBucketInventory.
Para visualizar uma configuração de inventário de bucket via API, consulte GetBucketInventory.
Para listar configurações de inventário de bucket via API, consulte ListBucketInventory.
Para excluir uma configuração de inventário de bucket via API, consulte DeleteBucketInventory.