Amazon S3: Read, Merge, and Remove Object Tags
See more S3 - REST Examples
Select read, merge, remove-one, or delete-all. Merge adds or replaces one named tag while preserving other tags from GetObjectTagging. Remove-one rebuilds the set without that key; delete-all uses DeleteObjectTagging. An empty tag value is valid. The replacement has at most 10 tags and includes a SHA-256 request checksum.
Tagging is read/modify/write, not an atomic conditional update. Coordinate concurrent tag writers; an ETag condition on the object is not a tag-set compare-and-swap. The returned version ID is reused when available to target that data version. For unversioned objects or the mutable null version, coordinate object writers as well as tag writers. Requires the corresponding Get/Put/DeleteObjectTagging permissions and their version-specific variants when versionId is used. Tags are distinct from user metadata.
For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.
Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.
Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.
AWS GetObjectTagging reference
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the S3 operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
success = credentials:load_file("qa_data/aws/s3.json")
if not success then
print("Could not load private AWS credentials.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("access_key"))
local sameText1 = textCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (sameText1) then
print("Missing or invalid access_key.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("secret_key"))
local sameText2 = textCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (sameText2) then
print("Missing or invalid secret_key.")
return
end
-- General purpose bucket in the commercial AWS partition.
local region = "us-west-2"
local bucketName = "amzn-s3-demo-bucket"
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(bucketName)
if not success then
print("Could not build text.")
return
end
success = endpoint:append(".")
if not success then
print("Could not build text.")
return
end
success = endpoint:append("s3.")
if not success then
print("Could not build text.")
return
end
success = endpoint:append(region)
if not success then
print("Could not build text.")
return
end
success = endpoint:append(".amazonaws.com")
if not success then
print("Could not build text.")
return
end
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "s3"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure AWS signing.")
return
end
-- Temporary credentials require this token in every signed query.
-- Keep request URLs private. Do not clear this parameter between requests.
if credentials:has_member("session_token") then
if credentials:json_type_of("session_token") ~= 1 then
print("session_token must be a string.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("session_token"))
local sameText3 = textCompare:contents_equal("", true)
if not sameText3 then
success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
if not success then
print("Could not prepare the request.")
return
end
end
end
-- Connect to the SAME hostname used for TLS verification and request signing.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
success = rest:use_connection(connection, true)
if not success then
print("Could not attach the TLS connection.")
return
end
local xml = chilkat.Xml.new()
xml.strict = true
-- Supply an unencoded object key, not a URL. Preserve slashes in the key.
local objectKey = "documents/example.txt"
local objectPath = chilkat.StringBuilder.new()
success = objectPath:append(objectKey)
if not success then
print("Could not build text.")
return
end
success = objectPath:encode("url_rfc3986", "utf-8")
if not success then
print("Could not encode the object key.")
return
end
local restoredSlashes = objectPath:replace("%2F", "/")
success = objectPath:prepend("/")
if not success then
print("Could not prepare the request.")
return
end
local operation = "merge"
local tagKey = "Environment"
local tagValue = "test"
textCompare:clear()
textCompare:set_string(operation)
local sameText4 = textCompare:contents_equal("read", true)
textCompare:clear()
textCompare:set_string(operation)
local sameText5 = textCompare:contents_equal("merge", true)
textCompare:clear()
textCompare:set_string(operation)
local sameText6 = textCompare:contents_equal("remove-one", true)
textCompare:clear()
textCompare:set_string(operation)
local sameText7 = textCompare:contents_equal("delete-all", true)
if (not sameText4) and ((not sameText5) and ((not sameText6) and (not sameText7))) then
print("Choose read, merge, remove-one, or delete-all.")
return
end
success = rest:add_query_param("tagging", "")
if not success then
print("Could not prepare the request.")
return
end
local responseBody = rest:full_request_no_body("GET", objectPath:get_as_string())
if not rest.last_method_success then
print("Request did not complete; inspect diagnostics privately.")
return
end
if rest.response_status_code ~= 200 then
print("S3 HTTP status: " .. rest.response_status_code)
success = xml:load_xml(responseBody)
textCompare:clear()
textCompare:set_string(xml.tag)
local sameText8 = textCompare:contents_equal("Error", true)
if (success) and (sameText8) then
print("S3 error code: " .. xml:get_child_content("Code"))
end
-- Keep signed headers, credentials, URLs, and full diagnostics private.
-- A timeout may leave a write's outcome uncertain. Check before retrying.
return
end
success = xml:load_xml(responseBody)
if not success then
print("Expected well-formed XML.")
return
end
textCompare:clear()
textCompare:set_string(xml.tag)
local sameText9 = textCompare:contents_equal("Tagging", true)
if not sameText9 then
print("Unexpected S3 response element; this is not a successful result.")
return
end
if not xml:has_child_with_tag("TagSet") then
print("Missing TagSet.")
return
end
-- Pin the version that was read when S3 returns its version ID.
local versionId = rest:response_hdr_by_name("x-amz-version-id")
if not rest.last_method_success then
versionId = ""
end
textCompare:clear()
textCompare:set_string(versionId)
local sameText10 = textCompare:contents_equal("", true)
if not sameText10 then
success = rest:add_query_param("versionId", versionId)
if not success then
print("Could not prepare the request.")
return
end
end
textCompare:clear()
textCompare:set_string(operation)
local sameText11 = textCompare:contents_equal("read", true)
if sameText11 then
print(xml:get_xml())
return
end
textCompare:clear()
textCompare:set_string(operation)
local sameText12 = textCompare:contents_equal("delete-all", true)
if sameText12 then
responseBody = rest:full_request_no_body("DELETE", objectPath:get_as_string())
if not rest.last_method_success then
print("Request did not complete; inspect diagnostics privately.")
return
end
if rest.response_status_code ~= 204 then
print("S3 HTTP status: " .. rest.response_status_code)
success = xml:load_xml(responseBody)
textCompare:clear()
textCompare:set_string(xml.tag)
local sameText13 = textCompare:contents_equal("Error", true)
if (success) and (sameText13) then
print("S3 error code: " .. xml:get_child_content("Code"))
end
-- Keep signed headers, credentials, URLs, and full diagnostics private.
-- A timeout may leave a write's outcome uncertain. Check before retrying.
return
end
print("All object tags removed.")
return
end
local replacement = chilkat.Xml.new()
replacement.tag = "Tagging"
success = replacement:add_attribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
if not success then
print("Could not prepare the request.")
return
end
replacement:new_child2("TagSet", "")
local seenKeys = chilkat.Hashtable.new()
local i = 0
local retained = 0
while i < xml:num_children_at("TagSet") do
xml.i = i
textCompare:clear()
textCompare:set_string(xml:get_child_content("TagSet|Tag[i]|Key"))
local sameText14 = textCompare:contents_equal("", true)
if (not xml:has_child_with_tag("TagSet|Tag[i]|Key")) or (sameText14) then
print("Missing response field: TagSet|Tag[i]|Key")
return
end
if not xml:has_child_with_tag("TagSet|Tag[i]|Value") then
print("Missing tag value.")
return
end
local existingKey = xml:get_child_content("TagSet|Tag[i]|Key")
if seenKeys:contains(existingKey) then
print("Duplicate key in returned tag set.")
return
end
success = seenKeys:add_int(existingKey, 1)
if not success then
print("Could not prepare the request.")
return
end
textCompare:clear()
textCompare:set_string(existingKey)
local sameText15 = textCompare:contents_equal(tagKey, true)
if not sameText15 then
replacement.i = retained
replacement:update_child_content("TagSet|Tag[i]|Key", existingKey)
replacement:update_child_content("TagSet|Tag[i]|Value", xml:get_child_content("TagSet|Tag[i]|Value"))
retained = retained + 1
end
i = i + 1
end
textCompare:clear()
textCompare:set_string(operation)
local sameText16 = textCompare:contents_equal("merge", true)
if sameText16 then
replacement.i = retained
replacement:update_child_content("TagSet|Tag[i]|Key", tagKey)
replacement:update_child_content("TagSet|Tag[i]|Value", tagValue)
retained = retained + 1
end
if retained > 10 then
print("The resulting tag set exceeds 10 tags; no change was sent.")
return
end
local requestBody = replacement:get_xml()
local digest = chilkat.Crypt2.new()
digest.charset = "utf-8"
digest.hash_algorithm = "sha256"
digest.encoding_mode = "base64"
local checksumBase64 = digest:hash_string_enc(requestBody)
if not digest.last_method_success then
print("Could not calculate the content checksum.")
return
end
success = rest:add_header("x-amz-checksum-sha256", checksumBase64)
if not success then
print("Could not prepare the request.")
return
end
success = rest:add_header("Content-Type", "application/xml")
if not success then
print("Could not prepare the request.")
return
end
responseBody = rest:full_request_string("PUT", objectPath:get_as_string(), requestBody)
if not rest.last_method_success then
print("Request did not complete; inspect diagnostics privately.")
return
end
if rest.response_status_code ~= 200 then
print("S3 HTTP status: " .. rest.response_status_code)
success = xml:load_xml(responseBody)
textCompare:clear()
textCompare:set_string(xml.tag)
local sameText17 = textCompare:contents_equal("Error", true)
if (success) and (sameText17) then
print("S3 error code: " .. xml:get_child_content("Code"))
end
-- Keep signed headers, credentials, URLs, and full diagnostics private.
-- A timeout may leave a write's outcome uncertain. Check before retrying.
return
end
print("Updated tag set saved; unrelated tags were preserved from the read.")