import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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(InventoryOptionalFields.Size);
fields.add(InventoryOptionalFields.LastModifiedDate);
fields.add(InventoryOptionalFields.IsMultipartUploaded);
fields.add(InventoryOptionalFields.StorageClass);
fields.add(InventoryOptionalFields.ETag);
fields.add(InventoryOptionalFields.EncryptionStatus);
inventoryConfiguration.setOptionalFields(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().withFrequency(InventoryFrequency.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({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// 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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
const inventory = {
// Specify the ID of the inventory.
id: 'default',
// Specify whether to enable the bucket inventory feature for the bucket. Valid values: true and false.
isEnabled: false,
// (Optional) Specify the condition that is used to filter the objects in inventory lists. The following sample code provides an example on how to filter the objects by prefix:
prefix: 'ttt',
OSSBucketDestination: {
// Specify the format of inventory lists.
format: 'CSV',
// Specify the ID of the Alibaba Cloud account to which the inventory storage bucket belongs.
accountId: '<Your AccountId>',
// Specify the name of the RAM role that is used to access the inventory storage bucket.
rolename: 'AliyunOSSRole',
// Specify the name of the inventory storage bucket.
bucket: '<Your BucketName>',
// (Optional) Specify the prefix of the path in which you want to store the generated inventory lists.
prefix: '<Your Prefix>',
// The following sample code provides an example on how to encrypt the inventory lists by using OSS-managed keys (SSE-OSS):
//encryption: {'SSE-OSS': ''},
// The following sample code provides an example on how to encrypt the inventory lists by using CMKs managed by KMS (SSE-KMS):
/*
encryption: {
'SSE-KMS': {
keyId: 'test-kms-id',
};,
*/
},
// Specify the frequency at which inventory lists are generated. A value of Weekly specifies that inventory lists are generated on a weekly basis. A value of Daily specifies that inventory lists are generated on a daily basis.
frequency: 'Daily',
// Specify that all versions of the objects are included in inventory lists. If includedObjectVersions is set to Current, only the current versions of the objects are included in inventory lists.
includedObjectVersions: 'All',
optionalFields: {
// (Optional) Specify the object attributes that you want to include in inventory lists.
field: ["Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus"]
},
}
async function putInventory(){
// Specify the name of the bucket for which you want to configure an inventory.
const bucket = '<Your BucketName>';
try {
await client.putBucketInventory(bucket, inventory);
console.log('An inventory is configured.')
} catch(err) {
console.log('Failed to configure an inventory: ', err);
}
}
putInventory()
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import (InventoryConfiguration,
InventoryFilter,
InventorySchedule,
InventoryDestination,
InventoryBucketDestination,
INVENTORY_INCLUDED_OBJECT_VERSIONS_CURRENT,
INVENTORY_FREQUENCY_DAILY,
INVENTORY_FORMAT_CSV,
FIELD_SIZE,
FIELD_LAST_MODIFIED_DATE,
FIELD_STORAG_CLASS,
FIELD_ETAG,
FIELD_IS_MULTIPART_UPLOADED,
FIELD_ENCRYPTION_STATUS)
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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.
# Specify the name of the bucket. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the ID of the account to which the bucket owner grants permissions to perform the operation. Example: 1283641033516515.
account_id = 'yourtBucketDestinationAccountId'
# Specify the name of the RAM role that is granted permissions to read all objects in the source bucket for which you want to configure the inventory and permissions to write data to the destination bucket in which you want to store the generated inventory lists. Example: acs:ram::1283641033516515:role/AliyunOSSRole.
role_arn = 'yourBucketDestinationRoleArn'
# Specify the name of the bucket in which you want to store the generated inventory lists.
dest_bucket_name = 'yourDestinationBucketName'
# Specify the inventory name.
inventory_id = "inventory1"
# Specify the object attributes that are included in the inventory lists.
optional_fields = [FIELD_SIZE, FIELD_LAST_MODIFIED_DATE, FIELD_STORAG_CLASS,
FIELD_ETAG, FIELD_IS_MULTIPART_UPLOADED, FIELD_ENCRYPTION_STATUS]
# Create the bucket in which you want to store the generated inventory lists.
bucket_destination = InventoryBucketDestination(
# Specify the ID of the account to which the destination bucket belongs.
account_id=account_id,
# Specify the ARN of the RAM role that you want to use to access the destination bucket.
role_arn=role_arn,
# Specify the name of the destination bucket.
bucket=dest_bucket_name,
# Specify the format of the inventory lists.
inventory_format=INVENTORY_FORMAT_CSV,
# Specify the prefix of the path in which you want to store the generated inventory lists.
prefix='destination-prefix',
# The following code provides an example on how to encrypt inventory lists by using customer master keys (CMKs) that are managed by Key Management Service (KMS).
# sse_kms_encryption=InventoryServerSideEncryptionKMS("test-kms-id"),
# The following code provides an example on how to encrypt the inventory lists on the OSS server.
# sse_oss_encryption=InventoryServerSideEncryptionOSS()
)
# Create an inventory.
inventory_configuration = InventoryConfiguration(
# Specify the ID of the inventory.
inventory_id=inventory_id,
# Specify whether to enable the inventory for the bucket. Valid values: true and false.
is_enabled=True,
# Specify whether to generate inventory lists on a daily or weekly basis. The following code provides an example on how to generate inventory lists on a daily basis. A value of Weekly indicates that inventory lists are generated on a weekly basis. A value of Daily indicates that inventory lists are generated on a daily basis.
inventory_schedule=InventorySchedule(frequency=INVENTORY_FREQUENCY_DAILY),
# Specify that inventory lists include only the current versions of objects. If you set the INVENTORY_INCLUDED_OBJECT_VERSIONS parameter to ALL, all versions of objects are included in inventory lists. This inventory takes effect only when versioning is enabled for the source bucket.
included_object_versions=INVENTORY_INCLUDED_OBJECT_VERSIONS_CURRENT,
# Specify the name prefix of objects that you want to include in inventory lists.
# inventory_filter=InventoryFilter(prefix="obj-prefix"),
# Specify conditions to filter inventory lists. For example, the beginning of the time range during which the object was last modified is 1637883649.
inventory_filter=InventoryFilter(
# Specify the prefix that is used to filter inventories.
"obj-prefix",
# Specify the beginning of the time range during which the object was last modified. Unit: seconds.
1637883649,
# Specify the end of the time range during which the object was last modified. Unit: seconds.
1638347592,
# Specify the minimum size of the object. Unit: B.
1024,
# Specify the maximum size of the object. Unit: B.
1048576,
# Specify the storage classes of objects.
'Standard,IA'),
# Specify the object attributes that you want to include in inventory lists.
optional_fields=optional_fields,
inventory_destination=InventoryDestination(bucket_destination=bucket_destination))
# Apply the inventory to the bucket.
result = bucket.put_bucket_inventory_configuration(inventory_configuration)
print(result.status)
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";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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(InventoryFrequency.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.OptionalFields.Add(InventoryOptionalField.Size);
config.OptionalFields.Add(InventoryOptionalField.LastModifiedDate);
config.OptionalFields.Add(InventoryOptionalField.StorageClass);
config.OptionalFields.Add(InventoryOptionalField.IsMultipartUploaded);
config.OptionalFields.Add(InventoryOptionalField.EncryptionStatus);
config.OptionalFields.Add(InventoryOptionalField.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);
}
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main() {
/// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
IsEnabled := true
// The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) managed by Key Management Service (KMS).
//var invEncryption oss.InvEncryption
//var invSseOss oss.InvSseOss
//var invSseKms oss.InvSseKms
//invSseKms.KmsId = "<yourKmsId>" // Specify the ID of CMK that is managed by KMS.
//invEncryption.SseOss = &invSseOss // Use OSS-managed keys (SSE-OSS) to encrypt the inventory lists.
//invEncryption.SseKms = &invSseKms // Use CMKs managed by KMS (SSE-KMS) to encrypt inventory lists.
invConfig := oss.InventoryConfiguration{
// Specify the name of the inventory. The name must be globally unique in the current bucket.
Id: "yourInventoryId2",
// Enable the inventory.
IsEnabled: &IsEnabled,
// Specify the rule that is used to filter the objects included in inventories. The following code provides an example on how to filter the objects by prefix.
Prefix: "yourFilterPrefix",
OSSBucketDestination: oss.OSSBucketDestination{
// Specify the format of the exported inventory lists.
Format: "CSV",
// Specify the ID of the account that is granted permissions by the bucket owner to perform the operation. Example: 109885487000****.
AccountId: "yourGrantAccountId",
// 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.
RoleArn: "yourRoleArn",
// Specify the name of the bucket in which you want to store the generated inventory lists.
Bucket: "acs:oss:::" + "yourDestBucketName",
// Specify the prefix of the path in which you want to store the generated inventory lists.
Prefix: "yourDestPrefix",
// The following sample code provides an example on how to encrypt inventory lists.
//Encryption: &invEncryption,
},
// Specify the frequency at which inventory lists are exported.
Frequency: "Daily",
// Specify whether to include all versions of objects or only the current versions of objects in the inventory lists.
IncludedObjectVersions: "All",
OptionalFields: oss.OptionalFields{
// Specify the fields that are included in inventory lists.
Field: []string{
"Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
},
},
}
// Specify the name of the bucket for which you want to configure the inventory.
err = client.SetBucketInventory("yourBucketName", invConfig)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
#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 name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
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;
}