Amazon Glacier: Upload Archive from a File
See more Amazon Glacier Examples
For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.
Computes both SHA-256 hashes, uploads immutable archive bytes, checks HTTP 201 and the returned tree hash, and prints the archive ID for durable storage in your catalog. A description is optional, must be printable ASCII, and is limited to 1,024 characters; it is not a lookup key. Single-request uploads support up to 4 GiB; use multipart upload for larger archives. This variant hashes and streams a file without buffering the full upload; the file must remain unchanged.
Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.
Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.
Chilkat Swift Downloads
func chilkatTest() {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
var success: Bool = false
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
let credentials = CkoJsonObject()!
credentials.strict = true
success = credentials.loadFile(path: "qa_data/aws/glacier.json")
if success != true {
print("Could not load private AWS credentials.")
return
}
if (credentials.jsonType(of: "access_key").intValue != 1) || (credentials.string(of: "access_key") == "") {
print("Missing or invalid access_key.")
return
}
if (credentials.jsonType(of: "secret_key").intValue != 1) || (credentials.string(of: "secret_key") == "") {
print("Missing or invalid secret_key.")
return
}
// Set this once to the region containing the vault.
var region: String? = "us-west-2"
let endpoint = CkoStringBuilder()!
endpoint.append(value: "glacier.")
endpoint.append(value: region)
endpoint.append(value: ".amazonaws.com")
let aws = CkoAuthAws()!
aws.accessKey = credentials.string(of: "access_key")
aws.secretKey = credentials.string(of: "secret_key")
aws.region = region
aws.serviceName = "glacier"
aws.signatureVersion = 4
let rest = CkoRest()!
rest.connectTimeoutMs = 20000
rest.idleTimeoutMs = 60000
success = rest.setAuthAws(authProvider: aws)
if success != true {
print("Could not configure AWS signing.")
return
}
// Temporary IAM/STS credentials require their session token on every signed request.
// Include the token in the signed query. Keep request URLs and diagnostics private.
// Leave session_token absent or empty only for credentials that do not have one.
if credentials.hasMember(jsonPath: "session_token") == true {
if credentials.jsonType(of: "session_token").intValue != 1 {
print("session_token must be a string.")
return
}
if credentials.string(of: "session_token") != "" {
success = rest.addQueryParam(name: "X-Amz-Security-Token", value: credentials.string(of: "session_token"))
if success != true {
print("Could not set the session-token parameter.")
return
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
let connection = CkoSocket()!
connection.requireSslCertVerify = true
connection.maxReadIdleMs = 60000
connection.maxSendIdleMs = 60000
success = connection.connect(hostname: endpoint.getAsString(), port: 443, ssl: true, maxWaitMs: 20000)
if success != true {
print("TLS connection failed; inspect diagnostics privately.")
return
}
success = rest.useConnection(connection: connection, autoReconnect: true)
if success != true {
print("Could not attach the TLS connection.")
return
}
success = rest.addHeader(name: "x-amz-glacier-version", value: "2012-06-01")
if success != true {
print("Could not set x-amz-glacier-version.")
return
}
// A hyphen selects the account belonging to the signing credentials.
// Use the original, URL-safe vault name and IDs returned by Glacier.
success = rest.addPathParam(name: "{vault}", value: "chilkat")
if success != true {
print("Could not set vault name.")
return
}
let body = CkoJsonObject()!
let result = CkoJsonObject()!
result.strict = true
let error = CkoJsonObject()!
error.strict = true
let requestBody = CkoStringBuilder()!
let responseBody = CkoStringBuilder()!
var filePath: String? = "qa_data/zips/somethingBig.zip"
// Keep this file unchanged during BOTH hashing passes and the upload.
let crypt = CkoCrypt2()!
crypt.hashAlgorithm = "sha256-tree-hash"
crypt.encodingMode = "hexlower"
let files = CkoFileAccess()!
var fileSize: String? = files.fileSizeStr(filePath: filePath)
if files.lastMethodSuccess != true {
print("Could not read archive file size.")
return
}
if fileSize == "0" {
crypt.hashAlgorithm = "sha256"
}
var treeHash: String? = crypt.hashFileENC(path: filePath)
if crypt.lastMethodSuccess != true {
print("Could not compute tree hash.")
return
}
success = rest.addHeader(name: "x-amz-sha256-tree-hash", value: treeHash)
if success != true {
print("Could not set x-amz-sha256-tree-hash.")
return
}
crypt.hashAlgorithm = "sha256"
var linearHash: String? = crypt.hashFileENC(path: filePath)
if crypt.lastMethodSuccess != true {
print("Could not compute payload hash.")
return
}
aws.precomputedSha256 = linearHash
// Set the precomputed hash before attaching the signing configuration again.
success = rest.setAuthAws(authProvider: aws)
if success != true {
print("Could not update AWS signing.")
return
}
success = rest.addHeader(name: "x-amz-content-sha256", value: linearHash)
if success != true {
print("Could not set x-amz-content-sha256.")
return
}
success = rest.addHeader(name: "x-amz-archive-description", value: "Example archive")
if success != true {
print("Could not set x-amz-archive-description.")
return
}
let fileStream = CkoStream()!
fileStream.sourceFile = filePath
rest.streamNonChunked = true
rest.idleTimeoutMs = 120000
connection.maxReadIdleMs = 120000
connection.maxSendIdleMs = 120000
var response: String? = rest.fullRequestStream(httpVerb: "POST", uriPath: "/-/vaults/{vault}/archives", stream: fileStream)
if rest.lastMethodSuccess != true {
print("Upload did not complete; check for an accepted archive before retrying.")
return
}
responseBody.append(value: response)
if rest.responseStatusCode.intValue != 201 {
print("Glacier HTTP status: \(rest.responseStatusCode.intValue)")
success = error.loadSb(sb: responseBody)
if success == true {
if error.jsonType(of: "code").intValue == 1 {
print("AWS error code: \(error.string(of: "code")!)")
}
}
print("AWS request ID: \(rest.responseHdr(byName: "x-amzn-RequestId")!)")
// Inspect full errors privately. An HTTP error is not a successful operation.
return
}
var archiveId: String? = rest.responseHdr(byName: "x-amz-archive-id")
if (rest.lastMethodSuccess != true) || (archiveId == "") {
print("Missing archive ID; investigate the accepted upload before retrying.")
return
}
// Save this ID even if subsequent checksum verification fails.
print("Archive ID: \(archiveId!)")
print("Location: \(rest.responseHdr(byName: "Location")!)")
var returnedHash: String? = rest.responseHdr(byName: "x-amz-sha256-tree-hash")
if returnedHash != treeHash {
print("Upload response checksum mismatch; preserve the archive ID and investigate.")
return
}
print("Archive upload verified. Persist its ID and checksum in your archive catalog.")
}