清空儲存區
本概述將重點介紹在 IBM Cloud® Object Storage 的一個實例中存取水桶中所有項目的清單,以便依序刪除每個項目所需的步驟。
任何必須在其 IBM Cloud Object Storage 實例中刪除儲存區的任何人都熟悉清空儲存區的程序,因為儲存區必須是空的才能刪除。 您可能有其他原因想要刪除項目,但想要避免個別刪除每一個物件。 受支援 SDK 的這個程式碼型樣可讓您定義配置、建立用戶端,然後與該用戶端連接,以取得已識別儲存區中所有項目的清單來刪除它們。
如果啟用版本化,則到期規則會建立 刪除標記。
最佳作法是避免將認證放入 Script 中。 此範例用於測試及教育用途,最佳作法及 開發人員指引 應該會通知您的特定設定。
開始之前
Python、Node.js、Java 及 Go 提供下載及安裝 SDK 的特定指示。 此外,當使用「指令行指示 (CLI)」及 CLI 用戶端時,請查看與 Object Storage 相關的相關資訊,例如 AWS 相容性、Minio 及 rclone。
對於此程式碼型樣,您將需要:
- IBM Cloud® Platform 帳戶
- IBM Cloud Object Storage 的實例
- 配置和操作使用IBM Cloud Object Storage SDK,供您選擇Java、Python、NodeJS,或 Go;或者,已設定且可操作的 CLI 用戶端。
使用主控台
在取得範例之前,有一種方法可以透過 IBM Cloud 主控台上的 GUI 來清空儲存區: 在儲存區本身使用有效期限規則。 如需相關資訊,請參閱 使用到期規則刪除舊資料 的相關文件。
登入 Object Storage 之後,選擇您的儲存實例。 然後,從儲存區清單中選取儲存區。 若要設定刪除項目的規則,請從導覽功能表中選擇組態,然後按一下到期規則部分下的新增規則。 將天數設為 '1',以在一天之後刪除所有項目。
規則完成的處理程序可能需要長達 24 小時,且符合設定的排程。 在應用這項技術時,請考慮這一點。
CLI 用戶端範例
有許多工具可協助使用者充分利用 Object Storage,下列 CLI 用戶端提供簡單的清空儲存區方法。
在 CLI 用戶端已配置且可運作之後,會提供使用用戶端應用程式或指令行的範例指示。
rclone 範例
rclone 工具通常用於保持目錄同步,以及在儲存平台之間遷移資料。 您可以從 使用 rclone 上的說明文件進一步瞭解。
rclone purge {remote}:{path} [flags]
Minio 範例
開放程式碼 Minio 用戶端可讓您將 UNIX 型指令 (ls、cp、cat 等) 與 IBM Cloud® Object Storage搭配使用。 如需相關資訊,請參閱 使用 Minio。
mc rm --recursive --force {instance-alias}/{bucket-name}
AWS 範例
AWS 的正式指令行介面與 IBM Cloud Object Storage S3 API 相容,您可以進一步瞭解如何 使用 AWS CLI。
aws s3 rm s3://{bucket-name} --recursive
程式碼範例
刪除整個目錄或移除儲存區的所有內容可能會耗費時間來刪除每一個物件,一次一個。 透過在刪除之前收集所有項目的清單,可以利用一次刪除一個項目的能力來節省時間和精力。
主題本身指出刪除的危險: 資料 將 遺失。 當然,當這是目標時,應謹慎行事,只應進行有針對性的刪除。 Check-and double-check-instances、儲存區名稱及任何需要指定的字首或路徑。
概觀
此練習中的程式碼型樣會在建立用戶端之前配置用戶端,以收集項目清單來刪除每一個物件。
此練習中的程式碼型樣會在建立用戶端之前配置用戶端,以收集項目清單來刪除每一個物件。
此練習中的程式碼型樣會在建立用戶端之前配置用戶端,以收集項目清單來刪除每一個物件。
此練習中的程式碼型樣會在建立用戶端之前配置用戶端,以收集項目清單來刪除每一個物件。
const myCOS = require('ibm-cos-sdk');
var config = {
endpoint: 's3.us-geo.cloud-object-storage.appdomain.cloud',
apiKeyId: 'd-2-DO-NOT-USEevplExampleo_t3ZTCJO',
ibmAuthEndpoint: 'https://iam.cloud.ibm.com/identity/token',
serviceInstanceId: 'crn:v1:bluemix:public:cloud-object-storage:global:a/SAMPLE253abf6e65dca920c9d58126b:3f656f43-5c2a-941e-b128-DO-NOT-USE::',
};
var cosClient = new myCOS.S3(config);
function logDone() {
console.log('COMPLETE!\n');
}
function logError(e) {
console.log(`ERROR: ${e.code} - ${e.message}\n`);
}
// Retrieve the list of contents from a bucket for deletion
function deleteContents(bucketName) {
var returnArr = new Array();
console.log(`Retrieving bucket contents from: ${bucketName}\n`);
return cosClient.listObjects(
{Bucket: bucketName},
).promise()
.then((data) => {
if (data != null && data.Contents != null) {
for (var i = 0; i < data.Contents.length; i++) {
returnArr.push(data.Contents[i].Key);
var itemKey = data.Contents[i].Key;
var itemSize = data.Contents[i].Size;
console.log(`Item: ${itemKey} (${itemSize} bytes).\n`)
}
deleteItem(bucketName, itemName);
logDone();
}
})
.catch(logError);
}
// Delete item
function deleteItem(bucketName, itemName) {
console.log(`Deleting item: ${itemName}`);
return cosClient.deleteObject({
Bucket: bucketName,
Key: itemName
}).promise()
.then(() =>{
console.log(`Item: ${itemName} deleted!`);
})
.catch(logError);
}
function main() {
try {
var BucketName = "<BUCKET_NAME>";
deleteContents(BucketName);
}
catch(ex) {
logError(ex);
}
}
main();
import ibm_boto3
from ibm_botocore.client import Config, ClientError
# Constants for IBM COS values
COS_ENDPOINT = "<endpoint>" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
COS_API_KEY_ID = "<api-key>" # eg "W00YiRnLW4a3fTjMB-odB-2ySfTrFBIQQWanc--P3byk"
COS_AUTH_ENDPOINT = "https://iam.cloud.ibm.com/identity/token"
COS_RESOURCE_CRN = "<resource-instance-id>" # eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003abfb5d29761c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"
# Create resource
cos = ibm_boto3.resource("s3",
ibm_api_key_id=COS_API_KEY_ID,
ibm_service_instance_id=COS_RESOURCE_CRN,
ibm_auth_endpoint=COS_AUTH_ENDPOINT,
config=Config(signature_version="oauth"),
endpoint_url=COS_ENDPOINT
)
def get_bucket_contents(bucket_name, max_keys):
print("Retrieving bucket contents from: {0}".format(bucket_name))
returnArray = []
try:
files = cos.Bucket(bucket_name).objects.all()
for file in files:
print("Item: {0} ({1} bytes).".format(file["Key"], file["Size"]))
returnArray.append(file["Key"])
except ClientError as be:
print("CLIENT ERROR: {0}\n".format(be))
except Exception as e:
print("Unable to retrieve bucket contents: {0}".format(e))
return returnArray
def delete_item(bucket_name, item_name):
print("Deleting item: {0}".format(item_name))
try:
cos.Object(bucket_name, item_name).delete()
print("Item: {0} deleted!".format(item_name))
except ClientError as be:
print("CLIENT ERROR: {0}\n".format(be))
except Exception as e:
print("Unable to delete item: {0}".format(e))
def main():
bucket = "<bucket_name>"
deleteListArray = get_bucket_contents(bucket, 1000)
for item_name in deleteListArray:
delete_item(bucket, item_name)
main()
package com.cos;
import java.sql.Timestamp;
import java.util.List;
import com.ibm.cloud.objectstorage.ClientConfiguration;
import com.ibm.cloud.objectstorage.SDKGlobalConfiguration;
import com.ibm.cloud.objectstorage.auth.AWSCredentials;
import com.ibm.cloud.objectstorage.auth.AWSStaticCredentialsProvider;
import com.ibm.cloud.objectstorage.auth.BasicAWSCredentials;
import com.ibm.cloud.objectstorage.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.ibm.cloud.objectstorage.services.s3.AmazonS3;
import com.ibm.cloud.objectstorage.services.s3.AmazonS3ClientBuilder;
import com.ibm.cloud.objectstorage.services.s3.model.Bucket;
import com.ibm.cloud.objectstorage.services.s3.model.ListObjectsRequest;
import com.ibm.cloud.objectstorage.services.s3.model.ListObjectsV2Request;
import com.ibm.cloud.objectstorage.services.s3.model.ListObjectsV2Result;
import com.ibm.cloud.objectstorage.services.s3.model.ObjectListing;
import com.ibm.cloud.objectstorage.services.s3.model.S3ObjectSummary;
import com.ibm.cloud.objectstorage.oauth.BasicIBMOAuthCredentials;
public class CosDeleteMultipleItems
{
private static AmazonS3 _cosClient;
/**
* @param args
*/
public static void main(String[] args)
{
SDKGlobalConfiguration.IAM_ENDPOINT = "https://iam.cloud.ibm.com/identity/token";
String bucketName = "<BUCKET_NAME>"; // eg my-unique-bucket-name
String newBucketName = "<NEW_BUCKET_NAME>"; // eg my-other-unique-bucket-name
String api_key = "<API_KEY>"; // eg "W00YiRnLW4k3fTjMB-oiB-2ySfTrFBIQQWanc--P3byk"
String service_instance_id = "<SERVICE_INSTANCE_ID"; // eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003abfb5d29761c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"
String endpoint_url = "https://s3.us.cloud-object-storage.appdomain.cloud"; // this could be any service endpoint
String storageClass = "us-geo";
String location = "us";
_cosClient = createClient(api_key, service_instance_id, endpoint_url, location);
contentsForDeletion(bucketName, 1000);
for(Int deletedItem: itemsForDeletion) {
deleteItem(bucketName, deletedItem.getKey());
System.out.printf("Deleted item: %s\n", deletedItem.getKey());
}
}
/**
* @param api_key
* @param service_instance_id
* @param endpoint_url
* @param location
* @return AmazonS3
*/
public static AmazonS3 createClient(String api_key, String service_instance_id, String endpoint_url, String location)
{
AWSCredentials credentials;
credentials = new BasicIBMOAuthCredentials(api_key, service_instance_id);
ClientConfiguration clientConfig = new ClientConfiguration().withRequestTimeout(5000);
clientConfig.setUseTcpKeepAlive(true);
AmazonS3 cosClient = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
.withEndpointConfiguration(new EndpointConfiguration(endpoint_url, location)).withPathStyleAccessEnabled(true)
.withClientConfiguration(clientConfig).build();
return cosClient;
}
public static List contentsForDeletion(String bucketName, int maxKeys) {
System.out.printf("Retrieving bucket contents (V2) from: %s\n", bucketName);
boolean moreResults = true;
String nextToken = "";
while (moreResults) {
ListObjectsV2Request request = new ListObjectsV2Request()
.withBucketName(bucketName)
.withMaxKeys(maxKeys)
.withContinuationToken(nextToken);
ListObjectsV2Result result = _cosClient.listObjectsV2(request);
for(S3ObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.printf("Item: %s (%s bytes)\n", objectSummary.getKey(), objectSummary.getSize());
deleteItem(bucketName, objectSummary.getKey());
}
if (result.isTruncated()) {
nextToken = result.getNextContinuationToken();
System.out.println("...More results in next batch!\n");
}
else {
nextToken = "";
moreResults = false;
}
}
System.out.println("...No more results!");
}
public static void deleteItem(String bucketName, String itemName) {
System.out.printf("Deleting item: %s\n", itemName);
_cosClient.deleteObject(bucketName, itemName);
System.out.printf("Item: %s deleted!\n", itemName);
}
}
import (
"github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
"github.com/IBM/ibm-cos-sdk-go/aws"
"github.com/IBM/ibm-cos-sdk-go/aws/session"
"github.com/IBM/ibm-cos-sdk-go/service/s3"
)
// Constants for IBM COS values
const (
apiKey = "<API_KEY>" // eg "0viPHOY7LbLNa9eLftrtHPpTjoGv6hbLD1QalRXikliJ"
serviceInstanceID = "<RESOURCE_INSTANCE_ID>" // "crn:v1:bluemix:public:cloud-object-storage:global:a/<CREDENTIAL_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
authEndpoint = "https://iam.cloud.ibm.com/identity/token"
serviceEndpoint = "<SERVICE_ENDPOINT>" // eg "https://s3.us.cloud-object-storage.appdomain.cloud"
bucketLocation = "<LOCATION>" // eg "us"
)
// Create config
conf := aws.NewConfig().
WithRegion("us-standard").
WithEndpoint(serviceEndpoint).
WithCredentials(ibmiam.NewStaticCredentials(aws.NewConfig(), authEndpoint, apiKey, serviceInstanceID)).
WithS3ForcePathStyle(true)
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Names
Bucket := "<BUCKET_NAME>"
Input := &s3.ListObjectsV2Input{
Bucket: aws.String(Bucket),
}
res, _ := client.ListObjectsV2(Input)
for _, item := range res.Contents {
input := &s3.DeleteObjectInput{
Bucket: aws.String(Bucket),
Key: aws.String(*item.Key),
}
d, _ := client.DeleteObject(input)
fmt.Println(d)
}
}
版本控制物件的大量刪除模式
curl 範例:
curl -X "POST" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/?delete" \
-H 'Authorization: bearer $TOKEN' \
-H 'Content-Type: text/xml' \
-d '<?xml version="1.0" encoding="UTF-8"?>
<Delete>
<Object>
<Key>my-object.txt</Key>
<VersionId>L4kqtJlcpXroDVBH40Nr8X8gdRQBpUMLUo</VersionId>
</Object>
<Object>
<Key>my-object.txt</Key>
<VersionId>YkXCFQHbwFpUTBeOZEJPnONBpQjFSbOo</VersionId>
</Object>
</Delete>'
Python 範例 (列出所有版本,然後批量刪除):
response = cosClient.list_object_versions(Bucket=BUCKET)
all_versions = [
{'Key': v['Key'], 'VersionId': v['VersionId']}
for v in response.get('Versions', []) + response.get('DeleteMarkers', [])
]
for i in range(0, len(all_versions), 1000):
cosClient.delete_objects(
Bucket=BUCKET,
Delete={'Objects': all_versions[i:i+1000]}
)
後續步驟
您可以在下列網址進一步探索利用此概觀所涵蓋之工具的新功能及現有功能: IBM Cloud 平台。