AWS 문서 예제 리포지토리에서 더 많은 SDK
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
또는 와 DeleteObject
AWS SDK 함께 사용 CLI
다음 코드 예제는 DeleteObject
의 사용 방법을 보여 줍니다.
작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
- .NET
-
- AWS SDK for .NET
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. 버저닝되지 않은 S3 버킷에서 객체를 삭제합니다.
using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete an object from a non-versioned Amazon /// Simple Storage Service (Amazon S3) bucket. /// </summary> public class DeleteObject { /// <summary> /// The Main method initializes the necessary variables and then calls /// the DeleteObjectNonVersionedBucketAsync method to delete the object /// named by the keyName parameter. /// </summary> public static async Task Main() { const string bucketName = "amzn-s3-demo-bucket"; const string keyName = "testfile.txt"; // If the Amazon S3 bucket is located in an AWS Region other than the // Region of the default account, define the AWS Region for the // Amazon S3 bucket in your call to the AmazonS3Client constructor. // For example RegionEndpoint.USWest2. IAmazonS3 client = new AmazonS3Client(); await DeleteObjectNonVersionedBucketAsync(client, bucketName, keyName); } /// <summary> /// The DeleteObjectNonVersionedBucketAsync takes care of deleting the /// desired object from the named bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client used to delete /// an object from an Amazon S3 bucket.</param> /// <param name="bucketName">The name of the bucket from which the /// object will be deleted.</param> /// <param name="keyName">The name of the object to delete.</param> public static async Task DeleteObjectNonVersionedBucketAsync(IAmazonS3 client, string bucketName, string keyName) { try { var deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = keyName, }; Console.WriteLine($"Deleting object: {keyName}"); await client.DeleteObjectAsync(deleteObjectRequest); Console.WriteLine($"Object: {keyName} deleted from {bucketName}."); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' when deleting an object."); } } }
버저닝된 S3 버킷에서 객체를 삭제합니다.
using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example creates an object in an Amazon Simple Storage Service /// (Amazon S3) bucket and then deletes the object version that was /// created. /// </summary> public class DeleteObjectVersion { public static async Task Main() { string bucketName = "amzn-s3-demo-bucket"; string keyName = "verstioned-object.txt"; // If the AWS Region of the default user is different from the AWS // Region of the Amazon S3 bucket, pass the AWS Region of the // bucket region to the Amazon S3 client object's constructor. // Define it like this: // RegionEndpoint bucketRegion = RegionEndpoint.USWest2; IAmazonS3 client = new AmazonS3Client(); await CreateAndDeleteObjectVersionAsync(client, bucketName, keyName); } /// <summary> /// This method creates and then deletes a versioned object. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to /// create and delete the object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where the /// object will be created and deleted.</param> /// <param name="keyName">The key name of the object to create.</param> public static async Task CreateAndDeleteObjectVersionAsync(IAmazonS3 client, string bucketName, string keyName) { try { // Add a sample object. string versionID = await PutAnObject(client, bucketName, keyName); // Delete the object by specifying an object key and a version ID. DeleteObjectRequest request = new DeleteObjectRequest() { BucketName = bucketName, Key = keyName, VersionId = versionID, }; Console.WriteLine("Deleting an object"); await client.DeleteObjectAsync(request); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } /// <summary> /// This method is used to create the temporary Amazon S3 object. /// </summary> /// <param name="client">The initialized Amazon S3 object which will be used /// to create the temporary Amazon S3 object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where the object /// will be created.</param> /// <param name="objectKey">The name of the Amazon S3 object co create.</param> /// <returns>The Version ID of the created object.</returns> public static async Task<string> PutAnObject(IAmazonS3 client, string bucketName, string objectKey) { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = objectKey, ContentBody = "This is the content body!", }; PutObjectResponse response = await client.PutObjectAsync(request); return response.VersionId; } }
-
자세한 API 내용은 참조DeleteObject의 섹션을 참조하세요. AWS SDK for .NET API
-
- Bash
-
- AWS CLI Bash 스크립트 사용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_item_in_bucket # # This function deletes the specified file from the specified bucket. # # Parameters: # $1 - The name of the bucket. # $2 - The key (file name) in the bucket to delete. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_item_in_bucket() { local bucket_name=$1 local key=$2 local response response=$(aws s3api delete-object \ --bucket "$bucket_name" \ --key "$key") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-object operation failed.\n$response" return 1 fi }
-
자세한 API 내용은 명령 참조DeleteObject의 섹션을 참조하세요. AWS CLI
-
- C++
-
- SDK C++용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. bool AwsDoc::S3::deleteObject(const Aws::String &objectKey, const Aws::String &fromBucket, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteObjectRequest request; request.WithKey(objectKey) .WithBucket(fromBucket); Aws::S3::Model::DeleteObjectOutcome outcome = client.DeleteObject(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error: deleteObject: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully deleted the object." << std::endl; } return outcome.IsSuccess(); }
-
자세한 API 내용은 참조DeleteObject의 섹션을 참조하세요. AWS SDK for C++ API
-
- CLI
-
- AWS CLI
-
다음 명령은 이름이
my-bucket
인 버킷에서test.txt
라는 객체를 삭제합니다.aws s3api delete-object --bucket
my-bucket
--keytest.txt
버킷 버전 관리가 활성화된 경우 출력에는 삭제 마커의 버전 ID가 포함됩니다.
{ "VersionId": "9_gKg5vG56F.TTEUdwkxGpJ3tNDlWlGq", "DeleteMarker": true }
객체 삭제에 대한 자세한 내용은 Amazon S3 개발자 안내서의 객체 삭제를 참조하세요.
-
자세한 API 내용은 명령 참조DeleteObject
의 섹션을 참조하세요. AWS CLI
-
- Go
-
- SDK Go V2용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. // S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // DeleteObject deletes an object from a bucket. func (actor S3Actions) DeleteObject(ctx context.Context, bucket string, key string, versionId string, bypassGovernance bool) (bool, error) { deleted := false input := &s3.DeleteObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), } if versionId != "" { input.VersionId = aws.String(versionId) } if bypassGovernance { input.BypassGovernanceRetention = aws.Bool(true) } _, err := actor.S3Client.DeleteObject(ctx, input) if err != nil { var noKey *types.NoSuchKey var apiErr *smithy.GenericAPIError if errors.As(err, &noKey) { log.Printf("Object %s does not exist in %s.\n", key, bucket) err = noKey } else if errors.As(err, &apiErr) { switch apiErr.ErrorCode() { case "AccessDenied": log.Printf("Access denied: cannot delete object %s from %s.\n", key, bucket) err = nil case "InvalidArgument": if bypassGovernance { log.Printf("You cannot specify bypass governance on a bucket without lock enabled.") err = nil } } } } else { deleted = true } return deleted, err }
-
자세한 API 내용은 참조DeleteObject
의 섹션을 참조하세요. AWS SDK for Go API
-
- Java
-
- SDK Java 2.x용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. /** * Deletes an object from an S3 bucket asynchronously. * * @param bucketName the name of the S3 bucket * @param key the key (file name) of the object to be deleted * @return a {@link CompletableFuture} that completes when the object has been deleted */ public CompletableFuture<Void> deleteObjectFromBucketAsync(String bucketName, String key) { DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() .bucket(bucketName) .key(key) .build(); CompletableFuture<DeleteObjectResponse> response = getAsyncClient().deleteObject(deleteObjectRequest); response.whenComplete((deleteRes, ex) -> { if (deleteRes != null) { logger.info(key + " was deleted"); } else { throw new RuntimeException("An S3 exception occurred during delete", ex); } }); return response.thenApply(r -> null); }
-
자세한 API 내용은 참조DeleteObject의 섹션을 참조하세요. AWS SDK for Java 2.x API
-
- JavaScript
-
- SDK 용 JavaScript (v3)
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. 객체를 삭제합니다.
import { DeleteObjectCommand, S3Client, S3ServiceException, waitUntilObjectNotExists, } from "@aws-sdk/client-s3"; /** * Delete one object from an Amazon S3 bucket. * @param {{ bucketName: string, key: string }} */ export const main = async ({ bucketName, key }) => { const client = new S3Client({}); try { await client.send( new DeleteObjectCommand({ Bucket: bucketName, Key: key, }), ); await waitUntilObjectNotExists( { client }, { Bucket: bucketName, Key: key }, ); // A successful delete, or a delete for a non-existent object, both return // a 204 response code. console.log( `The object "${key}" from bucket "${bucketName}" was deleted, or it didn't exist.`, ); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while deleting object from ${bucketName}. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while deleting object from ${bucketName}. ${caught.name}: ${caught.message}`, ); } else { throw caught; } } };
-
자세한 API 내용은 참조DeleteObject의 섹션을 참조하세요. AWS SDK for JavaScript API
-
- PHP
-
- PHP용 SDK
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. public function deleteObject(string $bucketName, string $fileName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args); try { $this->client->deleteObject($parameters); if ($this->verbose) { echo "Deleted the object named: $fileName from $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object deletion before continuing."; } throw $exception; } }
-
자세한 API 내용은 참조DeleteObject의 섹션을 참조하세요. AWS SDK for PHP API
-
- Python
-
- SDK Python용(Boto3)
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. 객체를 삭제합니다.
class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key def delete(self): """ Deletes the object. """ try: self.object.delete() self.object.wait_until_not_exists() logger.info( "Deleted object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) except ClientError: logger.exception( "Couldn't delete object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) raise
객체의 최신 버전을 삭제하여 객체를 이전 버전으로 롤백합니다.
def rollback_object(bucket, object_key, version_id): """ Rolls back an object to an earlier version by deleting all versions that occurred after the specified rollback version. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that holds the object to roll back. :param object_key: The object to roll back. :param version_id: The version ID to roll back to. """ # Versions must be sorted by last_modified date because delete markers are # at the end of the list even when they are interspersed in time. versions = sorted( bucket.object_versions.filter(Prefix=object_key), key=attrgetter("last_modified"), reverse=True, ) logger.debug( "Got versions:\n%s", "\n".join( [ f"\t{version.version_id}, last modified {version.last_modified}" for version in versions ] ), ) if version_id in [ver.version_id for ver in versions]: print(f"Rolling back to version {version_id}") for version in versions: if version.version_id != version_id: version.delete() print(f"Deleted version {version.version_id}") else: break print(f"Active version is now {bucket.Object(object_key).version_id}") else: raise KeyError( f"{version_id} was not found in the list of versions for " f"{object_key}." )
객체의 활성 삭제 마커를 제거하여 삭제된 객체를 다시 활성화합니다.
def revive_object(bucket, object_key): """ Revives a versioned object that was deleted by removing the object's active delete marker. A versioned object presents as deleted when its latest version is a delete marker. By removing the delete marker, we make the previous version the latest version and the object then presents as *not* deleted. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that contains the object. :param object_key: The object to revive. """ # Get the latest version for the object. response = s3.meta.client.list_object_versions( Bucket=bucket.name, Prefix=object_key, MaxKeys=1 ) if "DeleteMarkers" in response: latest_version = response["DeleteMarkers"][0] if latest_version["IsLatest"]: logger.info( "Object %s was indeed deleted on %s. Let's revive it.", object_key, latest_version["LastModified"], ) obj = bucket.Object(object_key) obj.Version(latest_version["VersionId"]).delete() logger.info( "Revived %s, active version is now %s with body '%s'", object_key, obj.version_id, obj.get()["Body"].read(), ) else: logger.warning( "Delete marker is not the latest version for %s!", object_key ) elif "Versions" in response: logger.warning("Got an active version for %s, nothing to do.", object_key) else: logger.error("Couldn't get any version info for %s.", object_key)
S3 객체에서 삭제 마커를 제거하는 Lambda 핸들러를 생성합니다. 이 핸들러를 사용하면 버전이 지정된 버킷에서 불필요한 삭제 마커를 효율적으로 정리할 수 있습니다.
import logging from urllib import parse import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logger.setLevel("INFO") s3 = boto3.client("s3") def lambda_handler(event, context): """ Removes a delete marker from the specified versioned object. :param event: The S3 batch event that contains the ID of the delete marker to remove. :param context: Context about the event. :return: A result structure that Amazon S3 uses to interpret the result of the operation. When the result code is TemporaryFailure, S3 retries the operation. """ # Parse job parameters from Amazon S3 batch operations invocation_id = event["invocationId"] invocation_schema_version = event["invocationSchemaVersion"] results = [] result_code = None result_string = None task = event["tasks"][0] task_id = task["taskId"] try: obj_key = parse.unquote(task["s3Key"], encoding="utf-8") obj_version_id = task["s3VersionId"] bucket_name = task["s3BucketArn"].split(":")[-1] logger.info( "Got task: remove delete marker %s from object %s.", obj_version_id, obj_key ) try: # If this call does not raise an error, the object version is not a delete # marker and should not be deleted. response = s3.head_object( Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id ) result_code = "PermanentFailure" result_string = ( f"Object {obj_key}, ID {obj_version_id} is not " f"a delete marker." ) logger.debug(response) logger.warning(result_string) except ClientError as error: delete_marker = error.response["ResponseMetadata"]["HTTPHeaders"].get( "x-amz-delete-marker", "false" ) if delete_marker == "true": logger.info( "Object %s, version %s is a delete marker.", obj_key, obj_version_id ) try: s3.delete_object( Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id ) result_code = "Succeeded" result_string = ( f"Successfully removed delete marker " f"{obj_version_id} from object {obj_key}." ) logger.info(result_string) except ClientError as error: # Mark request timeout as a temporary failure so it will be retried. if error.response["Error"]["Code"] == "RequestTimeout": result_code = "TemporaryFailure" result_string = ( f"Attempt to remove delete marker from " f"object {obj_key} timed out." ) logger.info(result_string) else: raise else: raise ValueError( f"The x-amz-delete-marker header is either not " f"present or is not 'true'." ) except Exception as error: # Mark all other exceptions as permanent failures. result_code = "PermanentFailure" result_string = str(error) logger.exception(error) finally: results.append( { "taskId": task_id, "resultCode": result_code, "resultString": result_string, } ) return { "invocationSchemaVersion": invocation_schema_version, "treatMissingKeysAs": "PermanentFailure", "invocationId": invocation_id, "results": results, }
-
API 자세한 내용은 DeleteObject의 AWS SDK Python(Boto3) API 참조 섹션을 참조하세요.
-
- Rust
-
- SDK Rust용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. /// Delete an object from a bucket. pub async fn remove_object( client: &aws_sdk_s3::Client, bucket: &str, key: &str, ) -> Result<(), S3ExampleError> { client .delete_object() .bucket(bucket) .key(key) .send() .await?; // There are no modeled errors to handle when deleting an object. Ok(()) }
-
API 자세한 내용은 Rust 참조 DeleteObject
의 섹션을 참조하세요. AWS SDK API
-
- SAP ABAP
-
- SDK 에 대한 SAP ABAP
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. TRY. lo_s3->deleteobject( iv_bucket = iv_bucket_name iv_key = iv_object_key ). MESSAGE 'Object deleted from S3 bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
-
API 자세한 내용은 DeleteObject의 AWS SDK SAP ABAP API 섹션을 참조하세요.
-
- Swift
-
- SDK Swift용
-
참고
에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import AWSS3 public func deleteFile(bucket: String, key: String) async throws { let input = DeleteObjectInput( bucket: bucket, key: key ) do { _ = try await client.deleteObject(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a file.")) throw error } }
-
API 자세한 내용은 Swift 참조 DeleteObject
의 섹션을 참조하세요. AWS SDK API
-