Você pode crie, consultar, listar e exclua configurações de inventário de um bucket do Object Storage Service (OSS).
Observações de uso
Neste tópico, utiliza-se o endpoint público da região china (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Create an OssClient instance.
Certifique-se de ter as permissões necessárias para crie, visualize, listar e exclua inventários de um bucket. Por padrão, o proprietário do bucket possui essas permissões. Caso você não tenha as permissões necessárias, solicite ao proprietário do bucket que as conceda.
É possível configure até 1.000 inventários por bucket.
O bucket de source e o bucket de destino que armazena as listas de inventário devem estar na mesma região.
Crie um inventário para um bucket
O código a seguir mostra como crie um inventário para um bucket:
#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(InventoryFrequency::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. */
InventoryOptionalFields field {
InventoryOptionalField::Size, InventoryOptionalField::LastModifiedDate,
InventoryOptionalField::ETag, InventoryOptionalField::StorageClass,
InventoryOptionalField::IsMultipartUploaded, InventoryOptionalField::EncryptionStatus
};
inventoryConf.setOptionalFields(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;
}
Consultar as configurações de inventário de um bucket
O código de exemplo a seguir consulta as configurações de inventário de um bucket:
#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";
/* Specify the name of the inventory. */
std::string InventoryId = "yourInventoryId";
/* 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);
/* Query the inventory configurations. */
auto outcome = client.GetBucketInventoryConfiguration(
GetBucketInventoryConfigurationRequest(BucketName, InventoryId));
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "Get Bucket Inventory fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Display information about the inventory. */
const auto& inventoryConf = outcome.result().InventoryConfiguration();
std::cout << inventoryConf.Id() << std::endl;
std::cout << inventoryConf.IsEnabled() << std::endl;
std::cout << inventoryConf.Filter().Prefix() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().AccountId() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().RoleArn() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().Bucket() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().Prefix() << std::endl;
if (inventoryConf.Destination().OSSBucketDestination().Encryption().hasSSEKMS()) {
std::cout << inventoryConf.Destination().OSSBucketDestination().Encryption().SSEKMS().KeyId() << std::endl;
}
else if (inventoryConf.Destination().OSSBucketDestination().Encryption().hasSSEOSS()) {
std::cout << "has sse-oss" << std::endl;
}
std::cout << static_cast<int>(inventoryConf.Schedule()) << std::endl;
std::cout << static_cast<int>(inventoryConf.IncludedObjectVersions()) << std::endl;
for (const auto& field: inventoryConf.OptionalFields()) {
std::cout << static_cast<int>(field) << std::endl;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Listar vários inventários de um bucket de uma só vez
É possível consultar até 100 inventários em uma única requisição. Para consultar mais de 100 inventários, envie múltiplas requisições e utilize o token retornado em cada resposta como parâmetro da requisição seguinte.
O código a seguir mostra como listar inventários configurados para um bucket:
#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);
/* Specify request parameters. */
std::string nextToken = "";
bool isTruncated = false;
do {
/* List the inventories. Up to 100 inventories can be listed per request. */
auto request = ListBucketInventoryConfigurationsRequest(BucketName);
request.setContinuationToken(nextToken);
auto outcome = client.ListBucketInventoryConfigurations(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ListObjects fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
break;
}
for (const auto& inventoryConf : outcome.result().InventoryConfigurationList()) {
std::cout << inventoryConf.Id() << std::endl;
std::cout << inventoryConf.IsEnabled() << std::endl;
std::cout << inventoryConf.Filter().Prefix() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().AccountId() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().RoleArn() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().Bucket() << std::endl;
std::cout << inventoryConf.Destination().OSSBucketDestination().Prefix() << std::endl;
if (inventoryConf.Destination().OSSBucketDestination().Encryption().hasSSEKMS()) {
std::cout << inventoryConf.Destination().OSSBucketDestination().Encryption().SSEKMS().KeyId() << std::endl;
}
else if (inventoryConf.Destination().OSSBucketDestination().Encryption().hasSSEOSS()) {
std::cout << "has sse-oss" << std::endl;
}
std::cout << static_cast<int>(inventoryConf.Schedule()) << std::endl;
std::cout << static_cast<int>(inventoryConf.IncludedObjectVersions()) << std::endl;
for (const auto& field: inventoryConf.OptionalFields()) {
std::cout << static_cast<int>(field) << std::endl;
}
}
nextToken = outcome.result().NextContinuationToken();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Exclua um inventário de um bucket
O código a seguir mostra como exclua um inventário configurado para um bucket:
#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";
/* Specify the name of the inventory. */
std::string InventoryId = "yourInventoryId";
/* 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);
/* Delete the inventory. */
auto outcome = client.DeleteBucketInventoryConfiguration(
DeleteBucketInventoryConfigurationRequest(BucketName, InventoryId));;
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "Delete Bucket Inventory fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Referências
Para mais informações sobre a operação de API que crie um inventário de bucket, consulte PutBucketInventory.
Para mais detalhes sobre a operação de API que consulta um inventário configurado em um bucket, consulte GetBucketInventory.
Para informações sobre a operação de API que lista inventários configurados em um bucket, consulte ListBucketInventory.
Para saber mais sobre a operação de API que exclua inventários configurados em um bucket, consulte DeleteBucketInventory.