清空存储区
此概述侧重于访问 IBM Cloud® Object Storage 实例中存储区中所有项的列表所需的步骤,以便按顺序删除每个项。
清空存储区的过程对于必须删除其实例 IBM Cloud Object Storage 中的存储区的任何人都很熟悉,因为要删除的存储区必须为空。 您可能希望删除项的其他原因,但希望避免单独删除每个对象。 受支持 SDK 的此 Code Pattern 将允许您定义配置,创建客户机,然后与该客户机连接以获取标识存储区中所有项的列表以将其删除。
如果启用了版本控制,那么到期规则将创建 删除标记。
最好避免将凭证放入脚本中。 此示例用于测试和教育目的,您的特定设置应由最佳实践和 开发者指南 提供参考。
准备工作
有关下载和安装 SDK 的特定指示信息可用于 Python,Node.js,Java 和 Go。 此外,在使用命令行指示信息 (CLI) 和 CLI 客户机时,请查看与 Object Storage 相关的有关 AWS 兼容性,Minio 和 rclone
的相关信息。
对于此 Code Pattern,您将需要:
- IBM Cloud® 平台帐户
- IBM Cloud Object Storage 的实例
- 配置并运行使用IBM Cloud Object Storage用于Java、Python、NodeJS,或 Go 的 SDK;或已配置并可运行的 CLI 客户端。
使用控制台
在获取示例之前,可以通过 GUI 在 IBM Cloud 控制台上使用存储区本身的到期规则来清空存储区。 有关更多信息,请参阅有关 使用到期规则删除旧数据 的文档。
登录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,存储区名称以及需要指定的任何前缀或路径。
概述
本练习中的 Code Pattern 在创建客户机之前配置了一个客户机,用于收集项目列表以删除每个对象。
本练习中的 Code Pattern 在创建客户机之前配置了一个客户机,用于收集项目列表以删除每个对象。
本练习中的 Code Pattern 在创建客户机之前配置了一个客户机,用于收集项目列表以删除每个对象。
本练习中的 Code Pattern 在创建客户机之前配置了一个客户机,用于收集项目列表以删除每个对象。
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)
}
}
后续步骤
利用本概述中涵盖的工具的新功能和现有功能,可以在以下位置进一步探索: IBM Cloud 平台。