日本語

Preventing File Overwrites in S3 with If-None-Match on AWS Emulator

​​AWS Emulator​Amazon S3,AWS CLI

When you put a file (object) into S3, adding --if-none-match "*" to aws s3api put-object makes the request fail with PreconditionFailed (HTTP 412) if a file with the same key already exists. When several processes try to write the same file name at once, this prevents a file that was written first from being overwritten, without a separate locking mechanism. Below are the commands and output from testing with AWS Emulator, without an AWS account.

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.624 (released November 26, 2026), and AWS CLI 2.42.4. I did not use an AWS account or credentials. I did not test how this behaves on real S3, its pricing, a bucket policy that requires conditional writes, the 409 Conflict that occurs when a delete happens at the same time, or --if-match, which compares ETags. Statements about real S3 are based on the official documentation. According to the AWS Emulator official documentation, AWS checks the emulator's behavior against the real service only in the US West (Oregon, us-west-2) Region (global services use us-east-1). The us-east-1 S3 used in this article is outside that scope.

Start the emulator and create a bucket

AWS Emulator is an emulator that accepts AWS API requests locally. According to the official documentation, no AWS account is needed, and requests are not sent to AWS. For installation and for the environment variables that point the AWS CLI at the emulator, see the separate articles "How to Install AWS Emulator on Ubuntu and Get Started" and "How to Store and Retrieve Files in S3 with AWS Emulator." In this article, I sent commands from a shell where I had set the environment variables from the official documentation, to an emulator started with aws-emulator -t off. -t off turns off the usage data (telemetry) that the emulator sends to AWS by default.

If the connection works, the user name in the ARN returned by aws sts get-caller-identity is emulator. (The 12-digit account ID is replaced.) Next, create a bucket and two files with different contents.

text
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator

$ aws s3 mb s3://example-bucket
make_bucket: example-bucket

$ echo "first" > first.txt; echo "second" > second.txt; cat first.txt second.txt
first
second

Without a flag, the file is silently overwritten

For comparison, first I put a file twice to the same key without any flag. The second put did not produce an error, and the contents changed to second, which was written last.

text
$ aws s3api put-object --bucket example-bucket --key plain.txt --body first.txt --query ETag
"\"eb260e9ae827821beceeed4104f0ad89\""

$ aws s3api put-object --bucket example-bucket --key plain.txt --body second.txt --query ETag
"\"59d0d19fc45ca69230d858f60a5557f8\""

$ aws s3 cp s3://example-bucket/plain.txt -
second

Put a file with –if-none-match "*"

According to the S3 User Guide page on conditional writes, the If-None-Match header makes the write happen only after confirming that no file with the same key exists in the bucket. The value is *. In the AWS CLI, write it as --if-none-match "*". Wrap it in quotes so the shell does not expand * into file names.

The first put succeeds because the key does not exist yet. The second put is rejected with PreconditionFailed, and the exit code was 254. The contents are still first from the first put.

text
$ aws s3api put-object --bucket example-bucket --key config.json --body first.txt --if-none-match "*"
{
    "ETag": "\"eb260e9ae827821beceeed4104f0ad89\"",
    "ChecksumCRC64NVME": "e5ThutavlkU=",
    "ChecksumType": "FULL_OBJECT",
    "ServerSideEncryption": "AES256"
}

$ aws s3api put-object --bucket example-bucket --key config.json --body second.txt --if-none-match "*"

aws: [ERROR]: An error occurred (PreconditionFailed) when calling the PutObject operation: At least one of the pre-conditions you specified did not hold

$ aws s3 cp s3://example-bucket/config.json -
first

I confirmed the HTTP status codes by extracting them from the --debug output. The request included the if-none-match:* header. It returned 412 when the key existed and 200 when it did not. The official documentation also says that the response is 412 Precondition Failed if a file with the same key exists, and 200 OK if it does not.

text
$ aws s3api put-object --bucket example-bucket --key config.json --body second.txt --if-none-match "*" --debug 2>&1 | grep -o -E "^if-none-match:.*|\"PUT /[^\"]*\" [0-9]+"
if-none-match:*
"PUT /example-bucket/config.json HTTP/1.1" 412

$ aws s3api put-object --bucket example-bucket --key new.json --body second.txt --if-none-match "*" --debug 2>&1 | grep -o -E "^if-none-match:.*|\"PUT /[^\"]*\" [0-9]+"
if-none-match:*
"PUT /example-bucket/new.json HTTP/1.1" 200

In a shell script, you can tell whether the write was rejected because the file already existed or because of some other failure by checking whether the error message contains PreconditionFailed.

text
$ if out=$(aws s3api put-object --bucket example-bucket --key config.json --body second.txt --if-none-match "*" 2>&1); then echo "置いた"; elif echo "$out" | grep -q PreconditionFailed; then echo "もうあるので置かなかった"; else echo "別の失敗: $out"; fi
もうあるので置かなかった

After you delete the file, you can write to the same key again.

text
$ aws s3api delete-object --bucket example-bucket --key config.json

$ aws s3api put-object --bucket example-bucket --key config.json --body second.txt --if-none-match "*" --query ETag
"\"59d0d19fc45ca69230d858f60a5557f8\""

$ aws s3 cp s3://example-bucket/config.json -
second

When five processes try to write at the same time

The official documentation says that when conditional writes to the same key overlap, the one that finishes first succeeds, and the others fail with 412. I tried writing five files with different contents to the same key, lock.txt, at the same time on the emulator. Only one succeeded, and the other four returned PreconditionFailed. The key holds the contents of the one that succeeded.

text
$ for i in 1 2 3 4 5; do (echo "writer-$i" > w$i.txt; if aws s3api put-object --bucket example-bucket --key lock.txt --body w$i.txt --if-none-match "*" >/dev/null 2>err$i.txt; then echo "writer-$i: 成功"; else echo "writer-$i: $(grep -o -E "\([A-Za-z]+\)" err$i.txt | head -1)"; fi) & done; wait
writer-3: 成功
writer-5: (PreconditionFailed)
writer-2: (PreconditionFailed)
writer-4: (PreconditionFailed)
writer-1: (PreconditionFailed)

$ aws s3 cp s3://example-bucket/lock.txt -
writer-3

The same conditional-writes page also says that if a delete finishes before a write, 409 Conflict may be returned, and that for PutObject you can simply retry.

You cannot add it to aws s3 cp

--if-none-match is an option for aws s3api commands such as put-object. In AWS CLI 2.42.4, I could not add it to the simpler aws s3 cp command.

text
$ aws s3 cp second.txt s3://example-bucket/config.json --if-none-match "*"

aws: [ERROR]: An error occurred (ParamValidation): Unknown options: --if-none-match, *

Also works with copies and multipart uploads

The official documentation lists CopyObject and CompleteMultipartUpload as APIs that accept If-None-Match, in addition to PutObject. With copy-object, the copy was rejected when the destination key had a file, and succeeded when it did not.

text
$ aws s3api copy-object --bucket example-bucket --key config.json --copy-source example-bucket/plain.txt --if-none-match "*"

aws: [ERROR]: An error occurred (PreconditionFailed) when calling the CopyObject operation: At least one of the pre-conditions you specified did not hold

$ aws s3api copy-object --bucket example-bucket --key config-copy.json --copy-source example-bucket/config.json --if-none-match "*" --query CopyObjectResult.ETag
"\"59d0d19fc45ca69230d858f60a5557f8\""

For a multipart upload, add --if-none-match "*" to the final complete-multipart-upload call. According to the official documentation, a file that is still being uploaded is not treated as written yet. If another process puts a file to the same key during that time, the later completion fails with 412. I reproduced this order on the emulator. After sending a 1 MB part, I put a different file (first.txt, 6 bytes) to the same key.

text
$ aws s3api create-multipart-upload --bucket example-bucket --key upload.bin --query UploadId --output text > upload-id.txt; cat upload-id.txt
gUCV2nDv4VK40QPzqmaBf2tw-mAQyY5jugL7NSwVNGM

$ head -c 1048576 /dev/urandom > part1.bin; aws s3api upload-part --bucket example-bucket --key upload.bin --part-number 1 --upload-id $(cat upload-id.txt) --body part1.bin --query ETag --output text > part1-etag.txt; cat part1-etag.txt
"58fccb5a0bcf30a7ade57f399145447f"

$ aws s3api put-object --bucket example-bucket --key upload.bin --body first.txt --if-none-match "*" --query ETag
"\"eb260e9ae827821beceeed4104f0ad89\""

$ printf "{\"Parts\":[{\"PartNumber\":1,\"ETag\":%s}]}\n" "$(jq -R . part1-etag.txt)" > parts.json; cat parts.json
{"Parts":[{"PartNumber":1,"ETag":"\"58fccb5a0bcf30a7ade57f399145447f\""}]}

$ aws s3api complete-multipart-upload --bucket example-bucket --key upload.bin --upload-id $(cat upload-id.txt) --multipart-upload file://parts.json --if-none-match "*"

aws: [ERROR]: An error occurred (PreconditionFailed) when calling the CompleteMultipartUpload operation: At least one of the pre-conditions you specified did not hold

$ aws s3api head-object --bucket example-bucket --key upload.bin --query ContentLength
6

The file left at the key is the 6-byte file that was written first. On the emulator, the rejected upload remained in progress and still appeared in the list.

text
$ aws s3api list-multipart-uploads --bucket example-bucket --query "Uploads[].Key"
[
    "upload.bin"
]

$ aws s3api abort-multipart-upload --bucket example-bucket --key upload.bin --upload-id $(cat upload-id.txt)
Warning

On real S3, the note on the conditional writes page recommends setting a lifecycle rule (AbortIncompleteMultipartUpload) that deletes incomplete multipart uploads after a set number of days, to keep storage costs down. On the emulator, the rejected upload stayed in progress, so I cancelled it with abort-multipart-upload above.

When no other write interferes, a completion with --if-none-match "*" goes through as normal, and the 1 MB file is created. I started over with a different key, report.bin, beginning from the upload itself. For the part, I reused part1.bin from above.

text
$ aws s3api create-multipart-upload --bucket example-bucket --key report.bin --query UploadId --output text > upload-id2.txt; cat upload-id2.txt
DTTIN7fT094pKWkQl9S1-t_3spAa0rO2wDD97uDeCSk

$ aws s3api upload-part --bucket example-bucket --key report.bin --part-number 1 --upload-id $(cat upload-id2.txt) --body part1.bin --query ETag --output text > part2-etag.txt; cat part2-etag.txt
"58fccb5a0bcf30a7ade57f399145447f"

$ printf "{\"Parts\":[{\"PartNumber\":1,\"ETag\":%s}]}\n" "$(jq -R . part2-etag.txt)" > parts2.json; cat parts2.json
{"Parts":[{"PartNumber":1,"ETag":"\"58fccb5a0bcf30a7ade57f399145447f\""}]}

$ aws s3api complete-multipart-upload --bucket example-bucket --key report.bin --upload-id $(cat upload-id2.txt) --multipart-upload file://parts2.json --if-none-match "*" --query Key
"report.bin"

$ aws s3api head-object --bucket example-bucket --key report.bin --query ContentLength
1048576

In a versioned bucket, only the current version is checked

According to the official documentation, in a bucket with versioning enabled, If-None-Match checks only the current version. If the current version is a delete marker, the write succeeds. On the emulator too, the put was rejected while the file existed, and succeeded after delete-object created a delete marker.

text
$ aws s3 mb s3://example-versioned
make_bucket: example-versioned

$ aws s3api put-bucket-versioning --bucket example-versioned --versioning-configuration Status=Enabled

$ aws s3api put-object --bucket example-versioned --key config.json --body first.txt --if-none-match "*" --query VersionId
"65b024f07e97c44e186a6c3fba3374ea"

$ aws s3api put-object --bucket example-versioned --key config.json --body second.txt --if-none-match "*"

aws: [ERROR]: An error occurred (PreconditionFailed) when calling the PutObject operation: At least one of the pre-conditions you specified did not hold

$ aws s3api delete-object --bucket example-versioned --key config.json
{
    "DeleteMarker": true,
    "VersionId": "7251fd1afe2b7166642883df2db1d1ab"
}

$ aws s3api put-object --bucket example-versioned --key config.json --body second.txt --if-none-match "*" --query VersionId
"c7246613ccd2bd4eab5d4212226dc6d9"

Looking at the version list, the first 6-byte version and the delete marker remain as older entries, and the newly written 7-byte version is now the current one.

text
$ aws s3api list-object-versions --bucket example-versioned --query "{Versions:Versions[].{IsLatest:IsLatest,Size:Size},DeleteMarkers:DeleteMarkers[].{IsLatest:IsLatest}}"
{
    "Versions": [
        {
            "IsLatest": true,
            "Size": 7
        },
        {
            "IsLatest": false,
            "Size": 6
        }
    ],
    "DeleteMarkers": [
        {
            "IsLatest": false
        }
    ]
}

In other words, even with --if-none-match "*", you can write a new file to a key after it has been deleted. This approach does not suit a design in which a key that has ever been used must never be written again.

​Posted by 86