Sample code for 30+ languages & platforms
Xojo Plugin Requires Chilkat v11.6.0+

Amazon Glacier: Delete Archives Listed in a Vault Inventory

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.

Permanently deletes archives when dryRun is false. Defaults to a local preview, which still downloads the inventory. Requires an unfiltered, complete CSV inventory job. Stop concurrent uploads and review the snapshot before live deletion. The inventory can omit recent uploads and still list recently deleted archives. The loop stops on the first failed deletion; earlier successful deletions are not rolled back.

There is no batch-delete API here: each archive uses DeleteArchive. Only HTTP 204 counts as success. This procedure does not prove the vault is empty; retrieve a refreshed inventory and satisfy DeleteVault requirements separately.

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.

AWS reference

Chilkat Xojo Plugin Downloads

Xojo Plugin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean
success = False
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the Glacier operation.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/glacier.json")
If (success <> True) Then
    System.DebugLog("Could not load private AWS credentials.")
    Return
End If

If ((credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "")) Then
    System.DebugLog("Missing or invalid access_key.")
    Return
End If

If ((credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "")) Then
    System.DebugLog("Missing or invalid secret_key.")
    Return
End If

//  Set this once to the region containing the vault.
Dim region As String
region = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("glacier.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "glacier"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If (success <> True) Then
    System.DebugLog("Could not configure AWS signing.")
    Return
End If

//  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("session_token") = True) Then
    If (credentials.JsonTypeOf("session_token") <> 1) Then
        System.DebugLog("session_token must be a string.")
        Return
    End If

    If (credentials.StringOf("session_token") <> "") Then
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
        If (success <> True) Then
            System.DebugLog("Could not set the session-token parameter.")
            Return
        End If

    End If

End If

//  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
    System.DebugLog("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection,True)
If (success <> True) Then
    System.DebugLog("Could not attach the TLS connection.")
    Return
End If

success = rest.AddHeader("x-amz-glacier-version","2012-06-01")
If (success <> True) Then
    System.DebugLog("Could not set x-amz-glacier-version.")
    Return
End If

//  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("{vault}","chilkat")
If (success <> True) Then
    System.DebugLog("Could not set vault name.")
    Return
End If

Dim body As New Chilkat.JsonObject
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim error As New Chilkat.JsonObject
error.Strict = True
Dim requestBody As New Chilkat.StringBuilder
Dim responseBody As New Chilkat.StringBuilder
//  Preview by default. Set false only after reviewing the complete inventory.
Dim dryRun As Boolean
dryRun = True
success = rest.AddPathParam("{job}","JOB_ID")
If (success <> True) Then
    System.DebugLog("Could not set job ID.")
    Return
End If

success = rest.FullRequestNoBodySb("GET","/-/vaults/{vault}/jobs/{job}",responseBody)
If (success <> True) Then
    System.DebugLog("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    Return
End If

If (rest.ResponseStatusCode <> 200) Then
    System.DebugLog("Glacier HTTP status: " + Str(rest.ResponseStatusCode))
    success = error.LoadSb(responseBody)
    If (success = True) Then
        If (error.JsonTypeOf("code") = 1) Then
            System.DebugLog("AWS error code: " + error.StringOf("code"))
        End If

    End If

    System.DebugLog("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
    //  Inspect full errors privately. An HTTP error is not a successful operation.
    Return
End If

success = result.LoadSb(responseBody)
If (success <> True) Then
    System.DebugLog("Expected valid JSON response.")
    Return
End If

If (result.JsonTypeOf("Completed") <> 5) Then
    System.DebugLog("Missing or invalid Completed.")
    Return
End If

If (result.JsonTypeOf("StatusCode") <> 1) Then
    System.DebugLog("Missing or invalid StatusCode.")
    Return
End If

If (result.StringOf("StatusCode") = "") Then
    System.DebugLog("Empty StatusCode.")
    Return
End If

If ((result.BoolOf("Completed") <> True) Or (result.StringOf("StatusCode") <> "Succeeded")) Then
    System.DebugLog("Job is not successfully complete. Check StatusCode and try later only if InProgress.")
    Return
End If

If (result.JsonTypeOf("Action") <> 1) Then
    System.DebugLog("Missing or invalid Action.")
    Return
End If

If (result.StringOf("Action") = "") Then
    System.DebugLog("Empty Action.")
    Return
End If

If (result.StringOf("Action") <> "InventoryRetrieval") Then
    System.DebugLog("Wrong job type.")
    Return
End If

If (result.StringOf("InventoryRetrievalParameters.Format") <> "CSV") Then
    System.DebugLog("This example requires a CSV inventory job.")
    Return
End If

If ((result.HasMember("InventoryRetrievalParameters.StartDate") = True) And (result.IsNullOf("InventoryRetrievalParameters.StartDate") <> True)) Then
    System.DebugLog("Use a complete, unfiltered inventory job for bulk deletion.")
    Return
End If

If ((result.HasMember("InventoryRetrievalParameters.EndDate") = True) And (result.IsNullOf("InventoryRetrievalParameters.EndDate") <> True)) Then
    System.DebugLog("Use a complete, unfiltered inventory job for bulk deletion.")
    Return
End If

If ((result.HasMember("InventoryRetrievalParameters.Limit") = True) And (result.IsNullOf("InventoryRetrievalParameters.Limit") <> True)) Then
    System.DebugLog("Use a complete, unfiltered inventory job for bulk deletion.")
    Return
End If

If ((result.HasMember("InventoryRetrievalParameters.Marker") = True) And (result.IsNullOf("InventoryRetrievalParameters.Marker") <> True)) Then
    System.DebugLog("Use a complete, unfiltered inventory job for bulk deletion.")
    Return
End If

If (result.JsonTypeOf("InventorySizeInBytes") <> 2) Then
    System.DebugLog("Missing or invalid InventorySizeInBytes.")
    Return
End If

Dim inventorySize As String
inventorySize = result.StringOf("InventorySizeInBytes")
Dim files As New Chilkat.FileAccess
Dim inventoryPath As String
inventoryPath = "qa_output/glacier-inventory.csv"
success = rest.FullRequestNoBodySb("GET","/-/vaults/{vault}/jobs/{job}/output",responseBody)
If (success <> True) Then
    System.DebugLog("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    Return
End If

If (rest.ResponseStatusCode <> 200) Then
    System.DebugLog("Glacier HTTP status: " + Str(rest.ResponseStatusCode))
    success = error.LoadSb(responseBody)
    If (success = True) Then
        If (error.JsonTypeOf("code") = 1) Then
            System.DebugLog("AWS error code: " + error.StringOf("code"))
        End If

    End If

    System.DebugLog("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
    //  Inspect full errors privately. An HTTP error is not a successful operation.
    Return
End If

success = responseBody.WriteFile(inventoryPath,"utf-8",False)
If (success <> True) Then
    System.DebugLog("Could not save CSV inventory.")
    Return
End If

Dim savedSize As String
savedSize = files.FileSizeStr(inventoryPath)
If ((files.LastMethodSuccess <> True) Or (savedSize <> inventorySize)) Then
    System.DebugLog("Inventory size mismatch; do not use this file.")
    Return
End If

Dim csv As New Chilkat.Csv
csv.HasColumnNames = True
success = csv.LoadFromString(responseBody.GetAsString())
If (success <> True) Then
    System.DebugLog("Invalid CSV inventory.")
    Return
End If

If (csv.GetColumnName(0) <> "ArchiveId") Then
    System.DebugLog("Unexpected inventory CSV columns.")
    Return
End If

If (csv.GetColumnName(1) <> "ArchiveDescription") Then
    System.DebugLog("Unexpected inventory CSV columns.")
    Return
End If

If (csv.GetColumnName(2) <> "CreationDate") Then
    System.DebugLog("Unexpected inventory CSV columns.")
    Return
End If

If (csv.GetColumnName(3) <> "Size") Then
    System.DebugLog("Unexpected inventory CSV columns.")
    Return
End If

If (csv.GetColumnName(4) <> "SHA256TreeHash") Then
    System.DebugLog("Unexpected inventory CSV columns.")
    Return
End If

//  Validate all IDs before sending the first DELETE.
Dim i As Int32
i = 0
While (i < csv.NumRows)
    If (csv.GetCellByName(i,"ArchiveId") = "") Then
        System.DebugLog("Empty archive ID; nothing will be deleted.")
        Return
    End If

    i = i + 1
Wend
i = 0
While (i < csv.NumRows)
    Dim archiveId As String
    archiveId = csv.GetCellByName(i,"ArchiveId")
    System.DebugLog("Inventory archive: " + archiveId)
    If (dryRun <> True) Then
        success = rest.AddPathParam("{archive}",archiveId)
        If (success <> True) Then
            System.DebugLog("Could not set archive ID.")
            Return
        End If

        success = rest.FullRequestNoBodySb("DELETE","/-/vaults/{vault}/archives/{archive}",responseBody)
        If (success <> True) Then
            System.DebugLog("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
            Return
        End If

        If (rest.ResponseStatusCode <> 204) Then
            System.DebugLog("Glacier HTTP status: " + Str(rest.ResponseStatusCode))
            success = error.LoadSb(responseBody)
            If (success = True) Then
                If (error.JsonTypeOf("code") = 1) Then
                    System.DebugLog("AWS error code: " + error.StringOf("code"))
                End If

            End If

            System.DebugLog("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
            //  Inspect full errors privately. An HTTP error is not a successful operation.
            Return
        End If

    End If

    i = i + 1
Wend
If (dryRun = True) Then
    System.DebugLog("Preview complete. No archives were deleted.")
Else
    System.DebugLog("Deleted the listed inventory archives. Vault emptiness is not confirmed.")
End If