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 {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫Bucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫存放清單結果的Bucket名稱。
String destBucketName ="yourDestinationBucketName";
// 填寫Bucket所有者授予的賬戶ID。
String accountId ="yourDestinationBucketAccountId";
// 填寫具有讀取源Bucket所有檔案和向目標Bucket寫入檔案許可權的角色名稱。
String roleArn ="yourDestinationBucketRoleArn";
// 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 建立OSSClient執行個體。
// 當OSSClient執行個體不再使用時,調用shutdown方法以釋放資源。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 建立清單配置。
InventoryConfiguration inventoryConfiguration = new InventoryConfiguration();
// 設定清單規則名稱。
String inventoryId = "testid";
inventoryConfiguration.setInventoryId(inventoryId);
// 設定清單中包含的Object屬性。
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);
// 設定清單的產生計劃,以下樣本為每周一次。其中,Weekly表示每周一次,Daily表示每天一次。
inventoryConfiguration.setSchedule(new InventorySchedule().withFrequency(InventoryFrequency.Weekly));
// 設定清單中包含的Object的版本為目前的版本。如果設定為InventoryIncludedObjectVersions.All則表示Object的所有版本在版本控制狀態下生效。
inventoryConfiguration.setIncludedObjectVersions(InventoryIncludedObjectVersions.Current);
// 清單配置是否啟用的標識,取值為true或者false,設定為true表示啟用清單配置,設定為false表示關閉清單配置。
inventoryConfiguration.setEnabled(true);
// 設定清單篩選規則,指定篩選Object的首碼。
InventoryFilter inventoryFilter = new InventoryFilter().withPrefix("obj-prefix");
inventoryConfiguration.setInventoryFilter(inventoryFilter);
// 建立存放清單結果的目標Bucket配置。
InventoryOSSBucketDestination ossInvDest = new InventoryOSSBucketDestination();
// 設定存放清單結果的儲存路徑首碼。
ossInvDest.setPrefix("destination-prefix");
// 設定清單格式。
ossInvDest.setFormat(InventoryFormat.CSV);
// 設定目標Bucket的使用者accountId。
ossInvDest.setAccountId(accountId);
// 設定目標Bucket的roleArn。
ossInvDest.setRoleArn(roleArn);
// 設定目標Bucket的名稱。
ossInvDest.setBucket(destBucketName);
// 如果需要使用KMS加密清單,請參考如下設定。
// InventoryEncryption inventoryEncryption = new InventoryEncryption();
// InventoryServerSideEncryptionKMS serverSideKmsEncryption = new InventoryServerSideEncryptionKMS().withKeyId("test-kms-id");
// inventoryEncryption.setServerSideKmsEncryption(serverSideKmsEncryption);
// ossInvDest.setEncryption(inventoryEncryption);
// 如果需要使用OSS服務端加密清單,請參考如下設定。
// InventoryEncryption inventoryEncryption = new InventoryEncryption();
// inventoryEncryption.setServerSideOssEncryption(new InventoryServerSideEncryptionOSS());
// ossInvDest.setEncryption(inventoryEncryption);
// 設定清單的目的地。
InventoryDestination destination = new InventoryDestination();
destination.setOssBucketDestination(ossInvDest);
inventoryConfiguration.setDestination(destination);
// 上傳清單配置。
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({
// yourregion填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為oss-cn-hangzhou。
region: 'yourregion',
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// 填寫儲存空間名稱。
bucket: 'yourbucketname'
});
const inventory = {
// 設定清單配置ID。
id: 'default',
// 清單配置是否啟用的標識,取值為true或false。
isEnabled: false,
//(可選)設定清單篩選規則,指定篩選object的首碼。
prefix: 'ttt',
OSSBucketDestination: {
// 設定清單格式。
format: 'CSV',
// 目標Bucket擁有者的帳號ID。
accountId: '<Your AccountId>',
// 目標Bucket的角色名稱。
rolename: 'AliyunOSSRole',
// 目標Bucket的名稱。
bucket: '<Your BucketName>',
//(可選)清單結果的儲存路徑首碼。
prefix: '<Your Prefix>',
// 如果需要使用SSE-OSS加密清單,請參考以下代碼。
//encryption: {'SSE-OSS': ''},
// 如果需要使用SSE-KMS加密清單,請參考以下代碼。
/*
encryption: {
'SSE-KMS': {
keyId: 'test-kms-id',
};,
*/
},
// 設定清單的產生計劃,WEEKLY對應每周一次,DAILY對應每天一次。
frequency: 'Daily',
// 設定清單結果中包含了Object的所有版本, 如果設定為Current,則表示僅包含Object的目前的版本。
includedObjectVersions: 'All',
optionalFields: {
//(可選)設定清單中包含的Object屬性。
field: ["Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus"]
},
}
async function putInventory(){
// 需要添加清單配置的Bucket名稱。
const bucket = '<Your BucketName>';
try {
await client.putBucketInventory(bucket, inventory);
console.log('清單配置添加成功')
} catch(err) {
console.log('清單配置添加失敗: ', err);
}
}
putInventory()
import argparse
import alibabacloud_oss_v2 as oss
# 建立命令列參數解析器,並描述指令碼用途:設定儲存空間清單(Inventory)
parser = argparse.ArgumentParser(description="put bucket inventory sample")
# 定義命令列參數,包括必需的地區、儲存空間名稱、endpoint、使用者ID、角色ARN以及清單名稱
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():
# 解析命令列參數,擷取使用者輸入的值
args = parser.parse_args()
# 從環境變數中載入訪問憑證資訊,用於身分識別驗證
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# 使用SDK預設配置建立設定物件,並設定認證提供者
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# 設定設定物件的地區屬性,根據使用者提供的命令列參數
cfg.region = args.region
# 如果提供了自訂endpoint,則更新設定物件中的endpoint屬性
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# 使用上述配置初始化OSS用戶端,準備與OSS互動
client = oss.Client(cfg)
# 發送請求以配置指定儲存空間的清單設定
result = client.put_bucket_inventory(oss.PutBucketInventoryRequest(
bucket=args.bucket, # 儲存空間名
inventory_id=args.inventory_id, # 儲存空間清單ID
inventory_configuration=oss.InventoryConfiguration(
included_object_versions='All', # 包含所有版本的對象
optional_fields=oss.OptionalFields(
fields=[ # 可選欄位,如大小和最後修改日期
oss.InventoryOptionalFieldType.SIZE,
oss.InventoryOptionalFieldType.LAST_MODIFIED_DATE,
],
),
id=args.inventory_id, # 儲存空間清單ID
is_enabled=True, # 啟用儲存空間清單
destination=oss.InventoryDestination(
oss_bucket_destination=oss.InventoryOSSBucketDestination(
format=oss.InventoryFormatType.CSV, # 輸出格式為CSV
account_id=args.user_id, # 使用者賬戶ID
role_arn=args.arn, # 角色ARN,具有讀取源儲存空間和寫入目標儲存空間的許可權
bucket=f'acs:oss:::{args.bucket}', # 目標儲存空間
prefix='aaa', # 資訊清單檔首碼
),
),
schedule=oss.InventorySchedule(
frequency=oss.InventoryFrequencyType.DAILY, # 清單頻率,這裡設定為每天
),
filter=oss.InventoryFilter(
lower_size_bound=1024, # 對象大小下限(位元組)
upper_size_bound=1048576, # 對象大小上限(位元組)
storage_class='ColdArchive', # 儲存類別篩選條件
prefix='aaa', # 對象首碼篩選條件
last_modify_begin_time_stamp=1637883649, # 最後修改時間戳記開始範圍
last_modify_end_time_stamp=1638347592, # 最後修改時間戳記結束範圍
),
),
))
# 列印操作結果的狀態代碼和請求ID,以便確認請求狀態
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
# 當此指令碼被直接執行時,調用main函數開始處理邏輯
if __name__ == "__main__":
main() # 指令碼進入點,控製程序流程從這裡開始
using Aliyun.OSS;
using Aliyun.OSS.Common;
// yourEndpoint填寫Bucket所在地區對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。
var endpoint = "yourEndpoint";
// 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 填寫Bucket名稱。
var bucketName = "examplebucket";
// 填寫Bucket所有者授予的賬戶ID。
var accountId ="yourDestinationBucketAccountId";
// 填寫具有讀取源Bucket所有檔案和向目標Bucket寫入檔案許可權的角色名稱。
var roleArn ="yourDestinationBucketRoleArn";
// 填寫存放清單結果的Bucket名稱。
var destBucketName ="yourDestinationBucketName";
// 填寫Bucket所在地區對應的Region。以華東1(杭州)為例,Region填寫為cn-hangzhou。
const string region = "cn-hangzhou";
// 建立ClientConfiguration執行個體,按照您的需要修改預設參數。
var conf = new ClientConfiguration();
// 設定v4簽名。
conf.SignatureVersion = SignatureVersion.V4;
// 建立OssClient執行個體。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// 添加Bucket清單。
var config = new InventoryConfiguration();
// 設定清單規則名稱。
config.Id = "report1";
// 清單配置是否啟用的標識,取值為true或false。設定為true,表示啟用清單配置。
config.IsEnabled = true;
// 設定清單篩選規則,指定篩選Object的首碼。
config.Filter = new InventoryFilter("filterPrefix");
// 建立清單的bucket目的地配置。
config.Destination = new InventoryDestination();
config.Destination.OSSBucketDestination = new InventoryOSSBucketDestination();
// 設定清單格式。
config.Destination.OSSBucketDestination.Format = InventoryFormat.CSV;
// 存放清單結果的目標Bucket的使用者accountId。
config.Destination.OSSBucketDestination.AccountId = accountId;
// 存放清單結果的目標Bucket的roleArn。
config.Destination.OSSBucketDestination.RoleArn = roleArn;
// 存放清單結果的目標Bucket名稱。
config.Destination.OSSBucketDestination.Bucket = destBucketName;
// 設定存放清單結果的儲存路徑首碼。
config.Destination.OSSBucketDestination.Prefix = "prefix1";
// 設定清單的產生計劃,以下樣本為每周一次。其中,Weekly對應每周一次,Daily對應每天一次。
config.Schedule = new InventorySchedule(InventoryFrequency.Daily);
// 設定清單中包含的object的版本為目前的版本。如果設定為InventoryIncludedObjectVersions.All則表示object的所有版本,在版本控制狀態下生效。
config.IncludedObjectVersions = InventoryIncludedObjectVersions.All;
// 設定清單中包含的Object屬性。
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);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* 初始化OSS帳號資訊。*/
/* yourEndpoint填寫Bucket所在地區對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。*/
std::string Endpoint = "yourEndpoint";
/* yourRegion填寫Bucket所在地區對應的Region。以華東1(杭州)為例,Region填寫為cn-hangzhou。*/
std::string Region = "yourRegion";
/* 填寫Bucket名稱,例如examplebucket。*/
std::string BucketName = "examplebucket";
/* 初始化網路等資源。*/
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
InventoryConfiguration inventoryConf;
/* 指定清單規則名稱,該名稱在當前Bucket下必須全域唯一。*/
inventoryConf.setId("inventoryId");
/* 清單配置是否啟用的標識,可選值為true或false。*/
inventoryConf.setIsEnabled(true);
/* (可選)清單篩選的首碼。指定首碼後,清單將篩選出符合首碼的Object。*/
inventoryConf.setFilter(InventoryFilter("objectPrefix"));
InventoryOSSBucketDestination dest;
/* 匯出資訊清單檔的檔案格式。*/
dest.setFormat(InventoryFormat::CSV);
/* 儲存空間擁有者的賬戶UID。*/
dest.setAccountId("10988548********");
/* 指定角色名稱,該角色需要擁有讀取源儲存空間所有檔案以及向目標儲存空間寫入檔案的許可權,格式為acs:ram::uid:role/rolename。*/
dest.setRoleArn("acs:ram::10988548********:role/inventory-test");
/* 存放匯出的資訊清單檔的儲存空間。*/
dest.setBucket("yourDstBucketName");
/* 資訊清單檔的儲存路徑首碼。*/
dest.setPrefix("yourPrefix");
/* (可選)資訊清單檔的加密方式, 可選SSEOSS或者SSEKMS方式加密。*/
//dest.setEncryption(InventoryEncryption(InventorySSEOSS()));
//dest.setEncryption(InventoryEncryption(InventorySSEKMS("yourKmskeyId")));
inventoryConf.setDestination(dest);
/* 資訊清單檔匯出的周期, 可選為Daily或者Weekly。*/
inventoryConf.setSchedule(InventoryFrequency::Daily);
/* 是否在清單中包含Object版本資訊, 可選為All或者Current。*/
inventoryConf.setIncludedObjectVersions(InventoryIncludedObjectVersions::All);
/* (可選)設定清單結果中應包含的配置項, 請按需配置。*/
InventoryOptionalFields field {
InventoryOptionalField::Size, InventoryOptionalField::LastModifiedDate,
InventoryOptionalField::ETag, InventoryOptionalField::StorageClass,
InventoryOptionalField::IsMultipartUploaded, InventoryOptionalField::EncryptionStatus
};
inventoryConf.setOptionalFields(field);
/* 設定清單配置。*/
auto outcome = client.SetBucketInventoryConfiguration(
SetBucketInventoryConfigurationRequest(BucketName, inventoryConf));
if (!outcome.isSuccess()) {
/* 異常處理。*/
std::cout << "Set Bucket Inventory fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* 釋放網路等資源。*/
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"
)
// 定義全域變數
var (
region string // 儲存地區
bucketName string // 儲存空間名稱
)
// init函數用於初始化命令列參數
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// 解析命令列參數
flag.Parse()
var (
accountId = "account id of the bucket" // 儲存空間所有者授予的賬戶ID,例如109885487000****
inventoryId = "inventory id" // 由使用者指定的清單名稱,清單名稱在當前Bucket下必須全域唯一
)
// 檢查bucket名稱是否為空白
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// 檢查region是否為空白
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// 載入預設配置並設定憑證提供者和地區
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// 建立OSS用戶端
client := oss.NewClient(cfg)
// 建立設定儲存空間清單的請求
putRequest := &oss.PutBucketInventoryRequest{
Bucket: oss.Ptr(bucketName), // 儲存空間名稱
InventoryId: oss.Ptr(inventoryId), // 由使用者指定的清單名稱
InventoryConfiguration: &oss.InventoryConfiguration{
Id: oss.Ptr(inventoryId), // 由使用者指定的清單名稱
IsEnabled: oss.Ptr(true), // 啟用清單配置
Filter: &oss.InventoryFilter{
Prefix: oss.Ptr("filterPrefix"), // 設定清單篩選規則,指定篩選Object的首碼
LastModifyBeginTimeStamp: oss.Ptr(int64(1637883649)), // 最後修改開始時間戳
LastModifyEndTimeStamp: oss.Ptr(int64(1638347592)), // 最後修改結束時間戳記
LowerSizeBound: oss.Ptr(int64(1024)), // 檔案大小下限(位元組)
UpperSizeBound: oss.Ptr(int64(1048576)), // 檔案大小上限(位元組)
StorageClass: oss.Ptr("Standard,IA"), // 儲存類型
},
Destination: &oss.InventoryDestination{
OSSBucketDestination: &oss.InventoryOSSBucketDestination{
Format: oss.InventoryFormatCSV, // 匯出資訊清單檔的檔案格式
AccountId: oss.Ptr(accountId), // 儲存空間所有者授予的賬戶ID,例如109885487000****
RoleArn: oss.Ptr("acs:ram::" + accountId + ":role/AliyunOSSRole"), // 儲存空間所有者授予操作許可權的角色名稱,比如acs:ram::109885487000****:role/ram-test
Bucket: oss.Ptr("acs:oss:::" + bucketName), // 存放匯出的清單結果的Bucket名稱
Prefix: oss.Ptr("export/"), // 存放清單結果的儲存路徑首碼
},
},
Schedule: &oss.InventorySchedule{
Frequency: oss.InventoryFrequencyDaily, // 資訊清單檔匯出的周期(每天)
},
IncludedObjectVersions: oss.Ptr("All"), // 是否在清單中包含Object的所有版本資訊
},
}
// 執行設定儲存空間清單的請求
putResult, err := client.PutBucketInventory(context.TODO(), putRequest)
if err != nil {
log.Fatalf("failed to put bucket inventory %v", err)
}
// 列印設定儲存空間清單的結果
log.Printf("put bucket inventory result:%#v\n", putResult)
}