I am trying to delete a large quantity of buckets spread out over different regions. I am having difficulty deleting all the objects in the buckets.
This command fails:
var objects = client.ListObjectsAsync(new ListObjectsRequest() { BucketName = bucket.BucketName }).Result;
With error:
The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint
I am guessing this is happening because my client is initialized in a different region.
How can I get objects from a bucket setting region dynamically?
Here is my full code:
var client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);
var buckets = client.ListBucketsAsync().Result;
foreach (var bucket in buckets.Buckets)
{
if (!keepList.Contains(bucket.BucketName))
{
var location = client.GetBucketLocationAsync(new GetBucketLocationRequest() { BucketName = bucket.BucketName }).Result;
var objects = client.ListObjectsV2Async(new ListObjectsV2Request() { BucketName = bucket.BucketName }).Result;
while (true)
{
if (objects.IsTruncated)
{
objects = client.ListObjectsV2Async(new ListObjectsV2Request() { BucketName = bucket.BucketName, ContinuationToken = objects.NextContinuationToken}).Result;
}
else
{
break;
}
}
var response = client.DeleteBucketAsync(new DeleteBucketRequest()
{
BucketName = bucket.BucketName,
BucketRegion = location.Location
}).Result;
}
}