حذف سیاستگذاری صندوقچه
برای حذف سیاست (Policy)های تعریفشده برای یک صندوقچه بهشکل زیر عمل میکنیم.
مولفهها
- کلیدهای احراز هویت
- نام صندوقچه
- NET.
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Reflection;
namespace DeleteBucketPolicy
{
class DeleteBucketPolicy
{
// This example shows how to check a bucket existence.
// The examples uses AWS SDK for .NET 3.5 and .NET 5.0.
private static IAmazonS3 _s3Client;
// Specify the name of the bucket to check.
private const string BUCKET_NAME = "<BUCKET_NAME>";
static async Task Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
await DeleteBucketPolicyAsync(_s3Client, BUCKET_NAME);
}
/// <summary>
/// DeleteBucketPolicyAsync calls the DoesS3BucketExistV2Async method
/// to set bucket's policies.
/// </summary>
/// <param name="client">The Amazon S3 client object.</param>
/// <param name="bucketName">The name of the bucket to check.</param>
static async Task DeleteBucketPolicyAsync(IAmazonS3 client, string bucketName)
{
// Delete current policy
DeleteBucketPolicyRequest deleteRequest = new DeleteBucketPolicyRequest
{
BucketName = bucketName,
};
Object policy = await client.DeleteBucketPolicyAsync(deleteRequest);
foreach (PropertyInfo prop in policy.GetType().GetProperties())
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(policy, null)}");
}
Console.WriteLine($"Policy successfully deleted from {bucketName} bucket");
}
}
}
<?php
require('client.php');
$bucket = $config['sample_bucket'];
// Deletes the policy from the bucket
try {
$resp = $client->deleteBucketPolicy([
'Bucket' => $bucket
]);
echo "Succeed in deleting policy of bucket: " . $bucket . "\n";
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket_name = 'sample_bucket'
bucket_policy = s3_resource.BucketPolicy(bucket_name)
bucket_policy.delete()
logging.info(bucket_policy.policy)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, DeleteBucketPolicyCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const run = async () => {
try {
const response = await s3.send(
new DeleteBucketPolicyCommand({
Bucket: 'sample_bucket',
})
);
console.log('Success', response);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Deletes the policy on a bucket. If the bucket doesn't exist, or there was
// and error an error message will be printed instead.
//
// Usage:
// go run s3_delete_bucket_policy.go BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name",
filepath.Base(os.Args[0]))
}
bucket := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Call S3 to delete the policy on the bucket.
_, err = svc.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{
Bucket: aws.String(bucket),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket {
// Special error handling for the when the bucket doesn't
// exists so we can give a more direct error message from the CLI.
exitErrorf("Bucket %q does not exist", bucket)
}
exitErrorf("Unable to delete bucket %q policy, %v", bucket, err)
}
fmt.Printf("Successfully deleted the policy on bucket %q.\n", bucket)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
برای اجرای قطعه کد بالا با فرض نامگذاری فایل کد به s3_delete_bucket_policy.go می توان از دستور زیر استفاده کرد:
go run s3_delete_bucket_policy.go BUCKET_NAME