物件鎖定

「物件鎖定」會保留電子記錄,並透過確保個別物件版本以 WORM (一寫多讀)、不可擦寫及不可重寫的方式儲存,來維護資料完整性。 在指定日期或移除任何合法保留之前,都會強制執行此原則。

為何使用物件鎖定?

Object Lock 透過對客戶的備份、災難回復及網路備援工作負載施行資料不可變性,來協助客戶控管資料保留及保留需求。

「物件鎖定」可確保 任何人都無法刪除資料,且 無法暫停物件上的保留。 在鎖定具有保留期的物件之前,請仔細閱讀文件。

使用「物件鎖定」時,您有責任確保符合您 (您的組織) 在長期保留及儲存資料時可能遵守的任何法規。

使用 Object Lock 時,您有責任確保您的 IBM Cloud 帳戶在資料受保存期限約束的整個期間內,均符合 IBM Cloud 的政策與指引,並維持良好狀態。 如需相關資訊,請參閱「IBM Cloud 服務」條款。

術語

有兩種方式使用「物件鎖定」來保護資料: 保留期間合法保留

  • 保留期間 定義無法修改或刪除物件的時間範圍。
  • 合法保留 也會防止變更物件,但只會保留到明確提升為止。

可以使用這些參數的任何組合-物件版本可以有一個、兩個或都沒有。

保留截止日期 (保留期間)

如果您需要在固定時間量內保護物件版本,則需要指定 保留截止日期,以決定無法變更的期間。 在過了此日期之後,可以刪除物件版本 (假設物件版本沒有合法保留)。 對於處於 GOVERNANCE 模式的物件,具備 權限 bypass-governance-retention 的授權使用者可在保留期限截止日前刪除該物件版本。

新物件的保留期間可以繼承自儲存區上設定的預設值,也可以在寫入物件時透過指定 保留截止日期來明確定義。

當您使用儲存區預設值時,未指定「保留截止日期」。 相反地,您可以指定持續時間 (以天或年為單位),在此期間,應該保護儲存區中放置的每個物件版本。 當您將物件放入儲存區時,會透過將指定的持續時間新增至物件寫入時間,來計算物件版本的「保留截止日期」。

如果您在儲存區中放置物件版本的要求包含明確保留模式及「保留至日期」,則那些設定會置換該物件版本的任何儲存區預設值。

與所有其他「物件鎖定」設定一樣,「保留截止日期」會套用至個別物件版本。 單一物件的不同版本可以具有不同的保留模式及期間。

假設物件在 90 天保留期的 60 天內,且您以相同的名稱及兩年保留期來改寫該物件。 作業將成功,並建立具有兩年保留期的物件新版本。 同時,在 30 天之後,原始版本即可刪除。

延長保留期

若要延長物件的保留期間,只需傳送要求來設定新的、較長的保留期間。 假設要求者具有 cloud-object-storage.object.put_object_lock_retentioncloud-object-storage.object.put_object_lock_retention_version 動作,則舊值將改寫為新的值。

縮短保留期限

對於受治理模式保護的物件,授權使用者可將保留期限提前至較早日期,前提是請求中包含 標頭 x-amz-bypass-governance-retention,且具備相應權限(cloud-object-storage.object.bypass_governance_retentioncloud-object-storage.object.put_object_lock_retentioncloud-object-storage.object.put_object_lock_retention_version)。

處於合規模式的物件,在保留期限屆滿前不得縮短或移除其保留期限。

Object Lock 入門指南

若要開始使用,有一些必要條件:

  • 您將需要儲存區上的 WriterManager 平台角色,或已指派適當動作 (例如 cloud-object-storage.bucket.put_object_lock_configuration) 的自訂角色。
  • 必須啟用物件版本化
  • 您將需要使用「標準」定價方案,如需詳細資料,請參閱 定價
  • 您需要挑選支援「物件鎖定」的區域,如需詳細資料,請參閱 整合式服務
  • 支援預設保留期間上限 100 年 (或 36500 天)。
  • 使用主控台時,除了天數或年數之外,也可以設定「保留截止日期」(以月為單位)。

合規模式下,物件的保留期限不得縮短。 在「治理」模式下,具備「BypassGovernanceRetention」權限的授權使用者可視需要縮短或移除保留期限。 在驗證測試階段,建議採用較短的預設保留時間(例如1天),並視需要進行調整。

建立並設定新儲存區以與物件鎖定搭配使用

  1. 導覽至您想要的 Object Storage 實例,並搭配使用 建立儲存區自訂儲存區選項
  2. 根據您的使用案例需求,輸入必要的儲存區配置詳細資料
  3. 導覽至 物件版本化 區段,並將它設為 已啟用
  4. 尋找 Immutability,並在「物件鎖定」下按一下 新增
  5. 將物件鎖定設為 已啟用
  6. 選擇性地設定預設保留期間。
  7. 按一下「儲存」
  8. 繼續進行其餘配置設定,然後按一下 建立儲存區

在現有儲存區上啟用物件鎖定:

可以設定儲存區以供「物件鎖定」使用,如下所示:

  1. 導覽至儲存區 配置 區段
  2. 按一下 物件版本化
  3. 在「物件版本化」區段中,按一下 編輯,將配置選項設為 已啟用儲存
  4. 導覽至 物件鎖定 區段,按一下 新增
  5. 物件鎖定 設為 已啟用
  6. 選擇性地設定預設保留期間。
  7. 點擊「儲存

將保留截止日期或法定保留新增至物件

  1. 導覽至具有目標物件的儲存區
  2. 切換 顯示版本
  3. 跳至目標版本的詳細資料
  4. 新增保留期間及/或切換合法保留。

使用物件鎖定來進行企業永續和災難回復

「物件鎖定」可用來在勒索軟體攻擊時提供服務的連續性,因為受保護資料無法修改或毀損。

一致性和資料完整性

雖然 IBM Cloud Object Storage 為所有資料 IO 作業提供了強大的一致性,但水桶組態最終會保持一致。 在儲存區上啟用、修改或刪除預設保留期間之後,配置可能需要一些時間才能在系統之間傳播。 物件上的作業 (例如新增合法保留) 會立即一致。

使用情形和會計

已鎖定物件 (及其版本) 提供使用情形,就像任何其他資料一樣,只要物件仍以保留期鎖定,您將負責 使用成本

互動

根據您的使用案例需求,「物件鎖定」可以與數個物件儲存體特性一起使用。

版本化

啟用版本化 是啟用「物件鎖定」的必要條件。 如果使用 x-amz-bucket-object-lock-enabled 標頭建立儲存區,則會自動啟用版本化。

刪除版本化物件會建立 刪除標記。 該物件可能看似已被刪除,但若物件處於受保護狀態,則在合規模式下無法刪除受保護版本。 刪除標記本身不受保護。 然而,對於處於「治理」模式下鎖定的物件,只要該物件未被法律保留令所約束,bypass-governance-retention 具備相應權限的授權使用者可在保留期限屆滿前刪除該物件。

抄寫

「物件鎖定」可與「複寫」功能搭配使用。 若在複製來源與目標儲存桶上皆已啟用「物件鎖定」,來源物件版本上的所有「物件鎖定」狀態都將複製到目標儲存桶。 這包括任何涉及繞過治理機制的 Object Lock 更新。 如需更多資訊,請參閱「物件複製」。

金鑰管理系統

受保護物件將使用儲存區的根金鑰進行加密。 在儲存區上啟用「物件鎖定」時,只要相關聯的儲存區已啟用「物件鎖定」,就會保護 Key Protect 或 Hyper Protect Crypto Services 所管理的根金鑰免於刪除。 這可防止加密解構受保護物件。

生命週期配置

可以啟用生命週期原則,保存已鎖定的物件,但自然無法啟用保留或合法保留下 使物件到期 的那些生命週期原則 (儲存區中未受保護的物件仍然可以過期)。

Immutable Object Storage

「物件鎖定」是使用 Immutable Object Storage時可用的保留原則的替代方案。 由於「物件鎖定」需要啟用版本化,且 Immutable Object Storage 與版本化不相容,因此無法在相同儲存區上同時啟用兩個 WORM 解決方案。 在「服務實例」中可以混合使用儲存區,每一個都使用 Immutable Object Storage 或「物件鎖定」。

物件標記

在受保護物件上新增或修改標籤沒有任何限制。

其他互動

在使用物件鎖與其他 Object Storage 功能(例如設定 CORS 政策、設定 IP 防火牆或基於條件的限制、水桶配額或 Code Engine )時,應該不會有任何不良互動。

IAM 動作

有新的 IAM 動作與「物件鎖定」相關聯。

IAM 動作
IAM 動作 角色
cloud-object-storage.bucket.get_object_lock_configuration 管理員、撰寫者、讀者
cloud-object-storage.bucket.put_object_lock_configuration 管理員、撰寫者
cloud-object-storage.object.get_object_lock_retention 管理員、撰寫者、讀者
cloud-object-storage.object.put_object_lock_retention 管理員、撰寫者
cloud-object-storage.object.get_object_lock_retention_version 管理員、撰寫者、讀者
cloud-object-storage.object.put_object_lock_retention_version 管理員、撰寫者
cloud-object-storage.object.get_object_lock_legal_hold 管理員、撰寫者、讀者
cloud-object-storage.object.put_object_lock_legal_hold 管理員、撰寫者
cloud-object-storage.object.get_object_lock_legal_hold_version 管理員、撰寫者、讀者
cloud-object-storage.object.put_object_lock_legal_hold_version 管理員、撰寫者
cloud-object-storage.object.bypass_governance_retention 管理員、撰寫者

請注意,具有「撰寫者」角色的使用者能夠讓物件在許多年 (可能是千年) 無法刪除。 請小心,並考量製作不容許大部分使用者設定「保留截止日期」的自訂角色。

Activity Tracker 事件

「物件鎖定」會產生其他事件。

  • cloud-object-storage.bucket-object-lock.create
  • cloud-object-storage.bucket-object-lock.read
  • cloud-object-storage.object-object-lock-legal-hold.create
  • cloud-object-storage.object-object-lock-legal-hold.read
  • cloud-object-storage.object-object-lock-retention.create
  • cloud-object-storage.object-object-lock-retention.read

對於 cloud-object-storage.bucket-object-lock.create 事件,下列欄位提供額外資訊:

欄位 說明
requestData.object_lock_configuration.enabled 指出已在儲存區上啟用物件鎖定
requestData.object_lock_configuration.defaultRetention.mode 表示 COMPLIANCEGOVERNANCE 模式已啟用。
object_lock_configuration.defaultRetention.years 預設保留期間 (以年為單位)。
object_lock_configuration.defaultRetention.days 預設保留期間 (以天為單位)。

只會呈現 object_lock_configuration.defaultRetention.yearsobject_lock_configuration.defaultRetention.days,但不能同時呈現兩者。

對於受保護物件上的作業,可能存在下列欄位:

欄位 說明
requestData.object_lock_protection.legal_hold 指出對物件版本有效的合法保留。
requestData.object_lock_protection.retention.mode 表示 COMPLIANCEGOVERNANCE 模式在物件版本上處於活躍狀態。
requestData.object_lock_protection.retention.retain_until_date 指出物件版本適合刪除的日期。 在此日期之後,物件不再根據保留日期來刪除受保護的物件。

REST API 範例

下列範例使用 cURL 顯示以方便使用。 環境變數用來代表使用者特定的元素,例如 $BUCKET$TOKEN$REGION。 請注意,$REGION 也會包含任何網路類型規格,因此使用專用網路將要求傳送至 us-south 中的儲存區需要將變數設為 private.us-south

在儲存區上啟用物件鎖定

「物件鎖定」配置在要求內文中以 XML 形式提供。 新要求將改寫儲存區上存在的任何現有抄寫規則。

「物件鎖定」配置必須包含一個規則。

選購標題
標頭 類型 說明
Content-MD5 字串 base64 對載荷進行了 128 位元 MD5 雜湊運算,此雜湊值用作完整性檢查,以確保載荷在傳輸過程中未遭篡改。
x-amz-checksum-crc32 字串 這個標頭是 Base64 編碼、32 位元 CRC32 物件的校驗和。
x-amz-checksum-crc32c 字串 這個標頭是 Base64 編碼、32 位元 CRC32C 物件的校驗和。
x-amz-checksum-crc64nvme 字串 這個標頭是 Base64 編碼、64 位元 CRC64NVME 物件的校驗和。 CRC64NVME 的校驗和永遠是完整物件的校驗和。
x-amz-checksum-sha1 字串 這個標頭是 Base64 編碼、160 位元的 SHA1 物件摘要。
x-amz-checksum-sha256 字串 這個標頭是 Base64 編碼、256 位元 SHA256 的物件摘要。
x-amz-sdk-checksum-algorithm 字串 表示使用 SDK 時,用來為物件建立校驗和的演算法。
x-amz-bypass-governance-retention 字串 此標頭允許授權使用者覆寫 GOVERNANCE 模式的保留設定,以便在物件的保留期限日期之前刪除或修改該物件。

Content-MD5 標頭或 checksum 標頭 (包括 x-amz-checksum-crc32, x-amz-checksum-crc32c, x-amz-checksum-crc64nvme, x-amz-checksum-sha1, 或 x-amz-checksum-sha256) 必須作為有效負載的完整性檢查。

要求的內文必須包含具有下列綱目的 XML 區塊:

元素 類型 子項 上代 限制
ObjectLockConfiguration 容器 ObjectLockEnabled, Rule 必要 限制 1。
ObjectLockEnabled 字串 ObjectLockConfiguration 必要 唯一有效值為 Enabled (區分大小寫)。
Rule 容器 DefaultRetention ObjectLockConfiguration 限制 1
DefaultRetention 容器 Days, Mode, Years Rule 限制 1。
Days 整數 DefaultRetention 您要針對預設保留期間指定的天數。 無法與 Years 結合。
Mode 字串 DefaultRetention COMPLIANCEGOVERNANCE (區分大小寫)。
Years 整數 DefaultRetention 您要為預設保留期指定的年數。 無法與 Days 結合。

此範例將保留任何新物件至少 30 天。

curl -X "PUT" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/?object-lock" \
     -H 'Authorization: bearer $TOKEN' \
     -H 'Content-MD5: exuBoz2kFBykNwqu64JZuA==' \
     -H 'Content-Type: text/plain; charset=utf-8' \
     -d $'<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
            <ObjectLockEnabled>Enabled</ObjectLockEnabled>
            <Rule>
                <DefaultRetention>
                  <Days>30</Days>
                  <Mode>COMPLIANCE</Mode>
                </DefaultRetention>
            </Rule>
          </ObjectLockConfiguration>'

成功要求會傳回 200 回應。

檢視儲存桶的「物件鎖定」設定

curl -X "GET" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/?object-lock" \
     -H 'Authorization: bearer $TOKEN'

這會傳回具有適當綱目的 XML 回應主體:

<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <ObjectLockEnabled>string</ObjectLockEnabled>
  <Rule>
      <DefaultRetention>
        <Days>30</Days>
        <Mode>COMPLIANCE</Mode>
      </DefaultRetention>
  </Rule>
</ObjectLockConfiguration>

新增或延長物件的保留期間

「物件鎖定」配置在要求內文中以 XML 形式提供。 新請求將覆寫物件上現有的任何複製規則,前提是該請求的 RetainUntilDate 設定值早於當前值,或物件處於 GOVERNANCE 模式下被鎖定,且請求者具備 權限 bypass-governance-retention

選用標頭
標頭 類型 說明
Content-MD5 字串 base64 對載荷進行了 128 位元 MD5 雜湊運算,此雜湊值用作完整性檢查,以確保載荷在傳輸過程中未遭篡改。
x-amz-checksum-crc32 字串 這個標頭是 Base64 編碼、32 位元 CRC32 物件的校驗和。
x-amz-checksum-crc32c 字串 這個標頭是 Base64 編碼、32 位元 CRC32C 物件的校驗和。
x-amz-checksum-crc64nvme 字串 這個標頭是 Base64 編碼、64 位元 CRC64NVME 物件的校驗和。 CRC64NVME 的校驗和永遠是完整物件的校驗和。
x-amz-checksum-sha1 字串 這個標頭是 Base64 編碼、160 位元的 SHA1 物件摘要。
x-amz-checksum-sha256 字串 這個標頭是 Base64 編碼、256 位元 SHA256 的物件摘要。
x-amz-sdk-checksum-algorithm 字串 表示使用 SDK 時,用來為物件建立校驗和的演算法。
x-amz-bypass-governance-retention 字串 此標頭允許授權使用者覆寫 GOVERNANCE 模式的保留設定,以便在物件的保留期限日期之前刪除或修改該物件。

Content-MD5 標頭或 checksum 標頭 (包括 x-amz-checksum-crc32, x-amz-checksum-crc32c, x-amz-checksum-crc64nvme, x-amz-checksum-sha1, 或 x-amz-checksum-sha256) 必須作為有效負載的完整性檢查。

您可以選擇性地指定要套用 RetainUntilDate 的版本。

選用的查詢參數

參數 必要? 類型 說明
versionID 選用 字串 版本 ID。

要求的內文必須包含具有下列綱目的 XML 區塊:

元素 類型 子項 上代 限制
Retention 容器 Mode, RetainUntilDate 必要 限制 1。
Mode 字串 Retention **必填 **COMPLIANCEGOVERNANCE (區分大小寫)。
RetainUntilDate 字串 Retention 必要 在 ISO8601 日期時間格式中可刪除物件之前的日期。

此範例將保留任何新物件至少到 2023 年 3 月 12 日為止。

curl -X "PUT" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/?retention" \
     -H 'Authorization: Bearer $TOKEN' \
     -H 'Content-MD5: fT0hYstki6zUvEh7abhcTA==' \
     -H 'Content-Type: text/plain; charset=utf-8' \
     -d $'<Retention>
            <Mode>COMPLIANCE</Mode>
            <RetainUntilDate>2023-03-12T23:01:00.000Z</RetainUntilDate>
          </Retention>'

成功要求會傳回 200 回應。

如果 RetainUntilDate 值未超出任何現有值,則作業會失敗,並產生 403 Access Denied

此範例縮短了在 GOVERNANCE 模式下受保護之現有物件版本的保留期限。 請求者必須具備繞過治理保留的權限。

curl -X "PUT" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/$OBJECT?retention" \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-MD5: fT0hYstki6zUvEh7abhcTA==" \
     -H "Content-Type: text/plain; charset=utf-8" \
     -H "x-amz-bypass-governance-retention: true" \
     -d $'<Retention>
            <Mode>GOVERNANCE</Mode>
            <RetainUntilDate>2023-02-10T23:01:00.000Z</RetainUntilDate>
          </Retention>'

成功的請求會返回 200 OK 狀態碼。 若請求者不 bypass-governance-retention 具備權限或缺少標頭,操作將因 403 存取遭拒而失敗。

新增或移除物件的合法保留

「物件鎖定」配置在要求內文中以 XML 形式提供。 新要求將改寫物件上呈現的任何現有抄寫規則,前提是 RetainUntilDate 在未來比現行值更遠。

選用標頭
標頭 類型 說明
Content-MD5 字串 base64 對載荷進行了 128 位元 MD5 雜湊運算,此雜湊值用作完整性檢查,以確保載荷在傳輸過程中未遭篡改。
x-amz-checksum-crc32 字串 這個標頭是 Base64 編碼、32 位元 CRC32 物件的校驗和。
x-amz-checksum-crc32c 字串 這個標頭是 Base64 編碼、32 位元 CRC32C 物件的校驗和。
x-amz-checksum-crc64nvme 字串 這個標頭是 Base64 編碼、64 位元 CRC64NVME 物件的校驗和。 CRC64NVME 的校驗和永遠是完整物件的校驗和。
x-amz-checksum-sha1 字串 這個標頭是 Base64 編碼、160 位元的 SHA1 物件摘要。
x-amz-checksum-sha256 字串 這個標頭是 Base64 編碼、256 位元 SHA256 的物件摘要。
x-amz-sdk-checksum-algorithm 字串 表示使用 SDK 時,用來為物件建立校驗和的演算法。

Content-MD5 標頭或 checksum 標頭 (包括 x-amz-checksum-crc32, x-amz-checksum-crc32c, x-amz-checksum-crc64nvme, x-amz-checksum-sha1, 或 x-amz-checksum-sha256) 必須作為有效負載的完整性檢查。

要求的內文必須包含具有下列綱目的 XML 區塊:

元素 類型 子項 上代 限制
legal-hold 容器 Status 限制 1。
Status 字串 legal-hold 支援的值為 ONOFF (區分大小寫)

此範例將保留任何新物件至少到 2023 年 3 月 12 日為止。

curl -X "PUT" "https://$BUCKET.s3.$REGION.cloud-object-storage.appdomain.cloud/?legal-hold&versionId=$VERSION_ID" \
     -H 'Authorization: Bearer $TOKEN' \
     -H 'Content-MD5: FMh6GxizXUBRaiDuB0vtgQ==' \
     -H 'Content-Type: text/plain; charset=utf-8' \
     -d $'<legal-hold>
            <Status>ON</Status>
          </legal-hold>'

成功要求會傳回 200 回應。

SDK 範例

以下範例採用適用於 Python、Node.js、Java 及 Go 的 IBM COS SDK,並搭配 Terraform 腳本。然而,物件版本控制的實作應能與任何允許設定自訂端點的 S3-compatible 函式庫或工具完全相容。 使用第三方工具需具備 HMAC 憑證,以計算 AWS V4 簽署。

Python

使用 IBM COS SDK for Python 啟用「物件鎖定」可以使用 低階用戶端 語法來完成。

使用用戶端:

import ibm_boto3
from ibm_botocore.client import Config
from ibm_botocore.exceptions import ClientError
from datetime import datetime, timedelta
import time

# Create new bucket with Object Lock enabled.
def create_bucket_with_objectlock(bucket_name):
        cos_cli.create_bucket(
            Bucket=bucket_name,
            ObjectLockEnabledForBucket=True,
        )
        print("Bucket: {0} created with objectlock enabled".format(bucket_name))

def objectlock_configuration_on_bucket(bucket_name):

    # Putting default retenion on the COS bucket.
    default_retention_rule = {'DefaultRetention': {'Mode': 'COMPLIANCE', 'Years': 1}}
    object_lock_config = {'ObjectLockEnabled': 'Enabled', 'Rule': default_retention_rule}
    cos_cli.put_object_lock_configuration(Bucket=bucket_name, ObjectLockConfiguration=object_lock_config)
    # Reading the objectlock configuration set on the bucket.
    response = cos_cli.get_object_lock_configuration(Bucket=bucket_name)
    print("Objectlock Configuration for {0} =>".format(bucket_name))
    print(response.ObjectLockConfiguration)

def objectlock_configuration_with_governance_mode_on_bucket(bucket_name):

    # Putting default retenion on the COS bucket with governance mode.
    default_retention_rule = {'DefaultRetention': {'Mode': 'GOVERNANCE', 'Years': 1}}
    object_lock_config = {'ObjectLockEnabled': 'Enabled', 'Rule': default_retention_rule}
    cos_cli.put_object_lock_configuration(Bucket=bucket_name, ObjectLockConfiguration=object_lock_config)
    # Reading the objectlock configuration set on the bucket.
    response = cos_cli.get_object_lock_configuration(Bucket=bucket_name)
    print("Objectlock Configuration for {0} =>".format(bucket_name))
    print(response.ObjectLockConfiguration)

def upload_object(bucket_name,object_name,object_content):
        cos_cli.put_object(
            Bucket=bucket_name,
            Key=object_name,
            Body=object_content
        )
        print("Object: {0} uploaded!".format(object_name))

def upload_object_with_governance_mode(bucket_name,object_name,object_content):
        cos_cli.put_object(
            Bucket=bucket_name,
            Key=object_name,
            Body=object_content,
            ObjectLockMode='GOVERNANCE',
            ObjectLockRetainUntilDate=datetime(2025, 11, 15)
        )
        print("Object: {0} uploaded!".format(object_name))

def objectlock_retention(bucket_name,object_name):
        # Put objectlock retenion on the  object uploaded to the bucket.
        date = datetime.now()+timedelta(seconds=5)
        retention_rule = {'Mode': 'COMPLIANCE', 'RetainUntilDate': date}
        cos_cli.put_object_retention(Bucket=bucket_name, Key=object_name, Retention=retention_rule)

        # Get objectlock retention of the above object.
        response = cos_cli.get_object_retention(Bucket=bucket_name, Key=object_name)
        print("Objectlock Retention for {0}=>".format(object_name))
        print(response.Retention)

def objectlock_retention_with_governance_mode(bucket_name,object_name):
        # Put objectlock retenion with governance mode on the  object uploaded to the bucket.
        date = datetime.now()+timedelta(seconds=5)
        retention_rule = {'Mode': 'GOVERNANCE', 'RetainUntilDate': date}
        cos_cli.put_object_retention(Bucket=bucket_name, Key=object_name, Retention=retention_rule)

        # Get objectlock retention of the above object.
        response = cos_cli.get_object_retention(Bucket=bucket_name, Key=object_name)
        print("Objectlock Retention for {0}=>".format(object_name))
        print(response.Retention)

def objectlock_legal_hold(bucket_name,object_name):
        # Setting the objectlock legal-hold status to ON.
        cos_cli.put_object_legal_hold(Bucket=bucket_name, Key=object_name, legal_hold={'Status': 'ON'})
        # Get objectlock retention of the above object.
        response = cos_cli.get_object_legal_hold(Bucket=bucket_name, Key=object_name)
        print("Objectlock legal-hold for {0}=>".format(object_name))
        print(response.legal_hold)

def delete_object_with_bypass_governance(bucket_name,object_name):
        # Deleting an object with retention using bypass governance
        cos_cli.delete_object(Bucket=bucket_name, Key=object_name, BypassGovernanceRetention=True)

COS_ENDPOINT = "" #Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints -> Ex:https://s3.us-south.cloud-object-storage.appdomain.cloud
COS_API_KEY_ID = "" #API Key of the cos instance created Ex: W00YixxxxxxxxxxMB-odB-2ySfTrFBIQQWanc--P3byk
COS_RESOURCE_INSTANCE_CRN = "" #API key of cos instance example: xxxd12V2QHXbjaM99G9tWyYDgF_0gYdlQ8aWALIQxXx4

# Create client connection
cos_cli = ibm_boto3.client("s3",
    ibm_api_key_id=COS_API_KEY_ID,
    config=Config(signature_version="oauth"),
    endpoint_url=COS_ENDPOINT,
    ibm_service_instance_id=COS_RESOURCE_INSTANCE_CRN,
    ibm_auth_endpoint="https://iam.cloud.ibm.com/identity/token"
)
new_bucket_name = "create-example-python12345" # bucket name should be unique gloablly, or else it will throw an error.
new_text_file_name = "cos_object.txt"
new_text_file_contents = "This is a test file from Python code sample!!!"

# *** Main Program ***
def main():
       create_bucket_with_objectlock(new_bucket_name) # Create a new cos bucket with object lock enabled.
       objectlock_configuration_on_bucket(new_bucket_name) # Put objectlock configuration(i.e. default retention) on COS bucket and get the configuration.
       objectlock_configuration_with_governance_mode_on_bucket(new_bucket_name) # Put objectlock configuration(i.e. default retention)with governance mode on COS bucket and get the configuration.
       upload_object(new_bucket_name,new_text_file_name,new_text_file_contents) # Upload an object to cos bucket.
       upload_object_with_governance_mode(new_bucket_name,new_text_file_name,new_text_file_contents) # Upload an object to cos bucket with governance mode.
       objectlock_retention(new_bucket_name,new_text_file_name) # Put objectlock retention(i.e. retain until date) on the object and get the configured retention.
       objectlock_retention_with_governance_mode(new_bucket_name,new_text_file_name) # Put objectlock retention(i.e. retain until date) with governance mode on the object and get the configured retention.
       objectlock_legal_hold(new_bucket_name,new_text_file_name)  # Put objectlock legal-hold on the object and get the legal-hold status.
       delete_object_with_bypass_governance(new_bucket_name,new_text_file_name) # Deleting an object with retention with governance mode using bypass governance.
if __name__ == "__main__":
    main()

Node.js

使用 IBM COS SDK for Node.js 啟用版本化:

'use strict';

// Required libraries
const ibm = require('ibm-cos-sdk');
const fs = require('fs');
const crypto = require('crypto');

function logError(e) {
    console.log(`ERROR: ${e.code} - ${e.message}\n`);
}

function logDone() {
    console.log('DONE!\n');
}

const COS_ENDPOINT = "";   //Choose endpoint from https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints. Ex: https://s3.us-south.cloud-object-storage.appdomain.cloud
const COS_API_KEY_ID = "";  // API key of cos instance example: xxxd12V2QHXbjaM99G9tWyYDgF_0gYdlQ8aWALIQxXx4
const COS_AUTH_ENDPOINT = "";
const COS_RESOURCE_INSTANCE_CRN = ""; // example: crn:v1:bluemix:public:cloud-object-storage:global:a <CREDENTIAL_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::

// Client Creation.
var config = {
    endpoint: COS_ENDPOINT,
    apiKeyId: COS_API_KEY_ID,
    ibmAuthEndpoint: COS_AUTH_ENDPOINT,
    serviceInstanceId: COS_RESOURCE_INSTANCE_CRN,
    signatureVersion: 'iam'
};

var cos = new ibm.S3(config);

// Create new bucket with objectlock enabled.
function createBucket(bucketName) {
    console.log(`Creating new bucket: ${bucketName}`);
    return cos.createBucket({
        Bucket: bucketName,
        ObjectLockEnabledForBucket: true,
        CreateBucketConfiguration: {
            LocationConstraint: ''
          },
    }).promise()
    .then((() => {
        console.log(`Bucket: ${bucketName} created!`);
    }))
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

// Create new text file and upload the object to COS bucket.
function createTextFile(bucketName, itemName, fileText) {
    console.log(`Creating new item: ${itemName}`);
    return cos.putObject({
        Bucket: bucketName,
        Key: itemName,
        Body: fileText
    }).promise()
    .then(() => {
        console.log(`Item: ${itemName} created!`);
        logDone();
    })
    .catch(logError);
}

function uploadFileWithGovernanceMode(bucketName, itemName, fileText) {
    var inFiveSecond = (new Date(Date.now() + (1000 * 5)))
    console.log(`Creating new item: ${itemName}`);
    return cos.putObject({
        Bucket: bucketName,
        Key: itemName,
        Body: fileText,
        ObjectLockMode: "GOVERNANCE",
        ObjectLockRetainUntilDate: inFiveSecond,

    }).promise()
    .then(() => {
        console.log(`Item: ${itemName} created!`);
        logDone();
    })
    .catch(logError);
}

function putObjectLockConfigurationOnBucket(bucketName) {
    console.log(`Putting Objectlock Configuration on : ${bucketName}`);
    // Putting objectlock configuration
    var defaultRetention = {Mode: 'COMPLIANCE', Days: 1}
    var objectLockRule = {DefaultRetention : defaultRetention}
    var param = {ObjectLockEnabled: 'Enabled', Rule: objectLockRule}
    return cos.putObjectLockConfiguration({
        Bucket: bucketName,
        ObjectLockConfiguration: param
    }).promise()
    .then(() => {
        console.log(`Object lock Configurtion added!!`);
        logDone();
    })
    .catch(logError);
}

function putObjectLockConfigurationWithGovernanceModeOnBucket(bucketName) {
    console.log(`Putting Objectlock Configuration on : ${bucketName}`);
    // Putting objectlock configuration
    var defaultRetention = {Mode: 'GOVERNANCE', Days: 1}
    var objectLockRule = {DefaultRetention : defaultRetention}
    var param = {ObjectLockEnabled: 'Enabled', Rule: objectLockRule}
    return cos.putObjectLockConfiguration({
        Bucket: bucketName,
        ObjectLockConfiguration: param
    }).promise()
    .then(() => {
        console.log(`Object lock Configurtion with Governance mode added!!`);
        logDone();
    })
    .catch(logError);
}

function getObjectLockConfigurationonBucket(bucketName) {
    console.log(`Getting Objectlock Configuration for : ${bucketName}`);
    // Getting objectlock configuration
    return cos.getObjectLockConfiguration({
        Bucket: bucketName,
    }).promise()
    .then((data) => {
        console.log(`objectlock configuration`);
        console.log( JSON.stringify(data.ObjectLockConfiguration, null, "    ") );
        logDone();
    })
    .catch(logError);
}

function putObjectLockRetention(bucketName,keyName) {
    console.log(`Putting Objectlock Retention on : ${keyName}`);
    var inFiveSecond = (new Date(Date.now() + (1000 * 5)))
    var rule = {Mode: 'COMPLIANCE', RetainUntilDate: inFiveSecond}
     // Putting objectlock retention
    return cos.putObjectRetention({
        Bucket: bucketName,
        Key: keyName,
        Retention: rule
    }).promise()
    .then(() => {
        console.log(`Object lock Retention added!!`);
        logDone();
    })
    .catch(logError);
}

function putObjectLockRetentionWithGovernanceMode(bucketName,keyName) {
    console.log(`Putting Objectlock Retention on : ${keyName}`);
    var inFiveSecond = (new Date(Date.now() + (1000 * 5)))
    var rule = {Mode: 'GOVERNANCE', RetainUntilDate: inFiveSecond}
     // Putting objectlock retention
    return cos.putObjectRetention({
        Bucket: bucketName,
        Key: keyName,
        Retention: rule
    }).promise()
    .then(() => {
        console.log(`Object lock Retention with governance mode added!!`);
        logDone();
    })
    .catch(logError);
}

function getObjectLockRetention(bucketName,keyName) {
    console.log(`Getting Objectlock Retention for : ${keyName}`);
    // Getting objectlock retention
    return cos.getObjectRetention({
        Bucket: bucketName,
        Key: keyName
    }).promise()
    .then((data) => {
        console.log(`Objectlock retention for : ${keyName} `);
        console.log( JSON.stringify(data.Retention, null, "    ") );
        logDone();
    })
    .catch(logError);
}

function putObjectLocklegalHold(bucketName,keyName) {
    console.log(`Putting Objectlock legal-hold status ON for  : ${keyName}`);
     // Putting objectlock legal-hold status
    return cos.putObjectlegalHold({
        Bucket: bucketName,
        Key: keyName,
        LegalHold: {Status: 'ON'}
    }).promise()
    .then(() => {
        console.log(`Object lock legal-hold added!!`);
        logDone();
    })
    .catch(logError);
}

function getObjectLocklegalHold(bucketName,keyName) {
    console.log(`Getting Objectlock legal-hold for : ${keyName}`);
    // Getting objectlock legal-hold
    return cos.getObjectlegal-hold({
        Bucket: bucketName,
        Key: keyName
    }).promise()
    .then((data) => {
        console.log(`Objectlock legal-hold for : ${keyName} `);
        console.log( JSON.stringify(data.legal-hold, null, "    ") );
        logDone();
    })
    .catch(logError);
}
function createBucket(bucketName,objectName) {
    console.log(`Deleting Object t: ${objectName}`);
    return cos.deleteObject({
  Bucket: bucketName,
  Key: objectName,
  BypassGovernanceRetention: true,
}).promise()
.then(() => {
    console.log("Object deleted");
})
.catch(err => {
    console.error("Error deleting object:", err);
});

}
// Main app
function main() {
    try {
        var newBucketName = "jscosbucket350";
        var newTextFileName = "js_cos_bucket_file.txt";
        var newTextFileContents = "This is a test file from Node.js code sample!!!";

        createBucket(newBucketName) // Create a new cos bucket with object lock enabled.
        .then(() => putObjectLockConfigurationOnBucket(newBucketName)) // Put objectlock configuration(i.e. default retention) on COS bucket.
        .then(() => putObjectLockConfigurationWithGovernanceModeOnBucket(newBucketName)) // Put objectlock configuration(i.e. default retention) with governance mode on COS bucket.
        .then(() => getObjectLockConfigurationonBucket(newBucketName)) // Read objectlock configuration on COS bucket.
        .then(() => createTextFile(newBucketName, newTextFileName, newTextFileContents)) // Upload an object with governance mode to cos bucket.
        .then(() => uploadFileWithGovernanceMode(newBucketName, newTextFileName, newTextFileContents)) // Upload an object to cos bucket.
        .then(() => putObjectLockRetention(newBucketName, newTextFileName)) // Put objectlock retention(i.e. retain until date) on the object.
        .then(() => putObjectLockRetentionWithGovernanceMode(newBucketName, newTextFileName)) // Put objectlock retention(i.e. retain until date) with governance mode on the object.
        .then(() => getObjectLockRetention(newBucketName, newTextFileName)) // Get the configured retention.
        .then(() => putObjectLocklegalHold(newBucketName,newTextFileName)) // Put objectlock legal-hold on the object.
        .then(() => getObjectLocklegalHold(newBucketName,newTextFileName))// Get the legal-hold status.
        .then(() => deleteObjectWithGovernanceMode(newBucketName,newTextFileName)); // Deleting an object with retention using bypass governance
    }
    catch(ex) {
        logError(ex);
    }
}

main();
```### Java
{: #ol-sdks-java}

```java {: codeblock}
mport com.ibm.cloud.objectstorage.ClientConfiguration;
import com.ibm.cloud.objectstorage.SDKGlobalConfiguration;
import com.ibm.cloud.objectstorage.auth.AWSCredentials;
import com.ibm.cloud.objectstorage.auth.AWSStaticCredentialsProvider;
import com.ibm.cloud.objectstorage.client.builder.AwsClientBuilder;
import com.ibm.cloud.objectstorage.oauth.BasicIBMOAuthCredentials;
import com.ibm.cloud.objectstorage.services.s3.AmazonS3;
import com.ibm.cloud.objectstorage.services.s3.AmazonS3ClientBuilder;
import com.ibm.cloud.objectstorage.services.s3.model.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

public class JavaExampleSDK {
    private static AmazonS3 _cosClient;
    private static String api_key;
    private static String service_instance_id;
    private static String endpoint_url;
    private static String location;
    private static String auth_endpoint;

    public static void main(String[] args) throws IOException
    {

        // Constants for IBM COS values
        auth_endpoint = ""; // auth endpoint
        api_key = "";// example: xxxd12V2QHXbjaM99G9tWyYDgF_0gYdlQ8aWALIQxXx4
        service_instance_id = ""; // example: crn:v1:bluemix:public:cloud-object-storage:global:a/xx999cd94a0dda86fd8eff3191349999:9999b05b-x999-4917-xxxx-9d5b326a1111::
        endpoint_url = ""; // example: https://s3.us-south.cloud-object-storage.appdomain.cloud
        location =  "";// example: us-south-standard

        // Create client connection details
        // _cosClient = createClient(api_key, service_instance_id, endpoint_url, location);

        // String bucketName = "java.bucket" + UUID.randomUUID().toString().replace("-","");
        // String itemName = UUID.randomUUID().toString().replace("-","") + "_java_file.txt";
        // String fileText = "This is a test file from the Java code sample!!!";

        // // create a new bucket
        // createBucket(bucketName, _cosClient);

        // // Put objectlock configuration(i.e. default retention) on COS bucket.
        // putObjectLockConfiguration(bucketName , _cosClient);

        // // Put objectlock configuration(i.e. default retention) with governance mode on COS bucket.
        // putObjectLockConfigurationWithGovernanceMode(bucketName , _cosClient);

        // // create a new text file & upload
        // createTextFileAndUpload(bucketName, itemName, fileText);
        // //  Upload an object with governance mode to cos bucket.
        // uploadFileWithGovernanceMode(bucketName, itemName, fileText);

        // //  Put objectlock retention(i.e. retain until date) on the object.
        // putObjectLockRetention(bucketName, itemName, _cosClient);
        // //  Put objectlock retention(i.e. retain until date) with governance mode on the object.
        // putObjectLockRetentionWithGovernanceMode(bucketName, itemName, _cosClient);

        // // remove the object with bypass governance
        // deleteObjectWithBypassGovernance(bucketName);
    }

    // Create client connection
    public static AmazonS3 createClient(String api_key, String service_instance_id, String endpoint_url, String location)
    {
        AWSCredentials credentials;
        credentials = new BasicIBMOAuthCredentials(api_key, service_instance_id);

        ClientConfiguration clientConfig = new ClientConfiguration().withRequestTimeout(5000);
        clientConfig.setUseTcpKeepAlive(true);

        AmazonS3 cosClient = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint_url, location)).withPathStyleAccessEnabled(true)
                .withClientConfiguration(clientConfig).build();
        return cosClient;
    }

    // Create a new bucket
    public static void createBucket(String bucketName, AmazonS3 _cosClient)
    {
        _cosClient.createBucket(bucketName);
        System.out.printf("Bucket: %s created!\n", bucketName);
    }

    // Put objectlock configuration(i.e. default retention) on COS bucket.
    public static void putObjectLockConfiguration(String bucketName, AmazonS3 _cosClient)
    {
        DefaultRetention defRet = new DefaultRetention()
                .withMode(ObjectLockRetentionMode.COMPLIANCE)
                .withDays(1);
        ObjectLockRule objRule = new ObjectLockRule()
                        .withDefaultRetention(defRet);
        ObjectLockConfiguration objConfig = new ObjectLockConfiguration()
                        .withObjectLockEnabled(ObjectLockEnabled.ENABLED)
                        .withRule(objRule);
        SetObjectLockConfigurationRequest objSet = new SetObjectLockConfigurationRequest()
                        .withBucketName(BUCKET_NAME)
                        .withObjectLockConfiguration(objConfig);
        _cosClient.setObjectLockConfiguration(objSet);
        System.out.printf("Successfully added object lock cofiguration on : %s\n", bucketName);
        GetObjectLockConfigurationRequest objReq = new GetObjectLockConfigurationRequest().withBucketName(BUCKET_NAME);
        GetObjectLockConfigurationResult objRes = _cosClient.getObjectLockConfiguration(objReq);
        ObjectLockConfiguration objLckConfig = objRes.getObjectLockConfiguration();
        ObjectLockRule objGetRule = objLckConfig.getRule();
        System.out.printf("ObjectLock Configuration : %s\n", objGetRule);
    }

    // Put objectlock configuration(i.e. default retention) with governance mode on COS bucket.
    public static void putObjectLockConfigurationWithGovernanceMode(String bucketName, AmazonS3 _cosClient)
    {
        DefaultRetention defRet = new DefaultRetention()
                .withMode(ObjectLockRetentionMode.GOVERNANCE)
                .withDays(1);
        ObjectLockRule objRule = new ObjectLockRule()
                        .withDefaultRetention(defRet);
        ObjectLockConfiguration objConfig = new ObjectLockConfiguration()
                        .withObjectLockEnabled(ObjectLockEnabled.ENABLED)
                        .withRule(objRule);
        SetObjectLockConfigurationRequest objSet = new SetObjectLockConfigurationRequest()
                        .withBucketName(BUCKET_NAME)
                        .withObjectLockConfiguration(objConfig);
        _cosClient.setObjectLockConfiguration(objSet);
        System.out.printf("Successfully added object lock cofiguration on : %s\n", bucketName);
        GetObjectLockConfigurationRequest objReq = new GetObjectLockConfigurationRequest().withBucketName(BUCKET_NAME);
        GetObjectLockConfigurationResult objRes = _cosClient.getObjectLockConfiguration(objReq);
        ObjectLockConfiguration objLckConfig = objRes.getObjectLockConfiguration();
        ObjectLockRule objGetRule = objLckConfig.getRule();
        System.out.printf("ObjectLock Configuration : %s\n", objGetRule);

    }

    // Create file and upload to new bucket
    public static void createTextFileAndUpload(String bucketName, String itemName, String fileText) {
        System.out.printf("Creating new item: %s\n", itemName);

        InputStream newStream = new ByteArrayInputStream(fileText.getBytes(Charset.forName("UTF-8")));
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileText.length());
        PutObjectRequest req = new PutObjectRequest(bucketName, itemName, newStream, metadata);
        _cosClient.putObject(req);
        System.out.printf("Item: %s created!\n", itemName);
    }

    //  Upload an object with governance mode to cos bucket.
    public static void uploadFileWithGovernanceMode(String bucketName, String itemName, String fileText) {
        System.out.printf("Creating new item: %s\n", itemName);
        LocalDate date = LocalDate.of(2025, 11, 11);
        InputStream newStream = new ByteArrayInputStream(fileText.getBytes(Charset.forName("UTF-8")));
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileText.length());
        PutObjectRequest req = new PutObjectRequest(bucketName, itemName, newStream, metadata)
                            .withObjectLockMode("GOVERNANCE")
                            .withObjectLockRetainUntilDate(date);
        _cosClient.putObject(req);
        System.out.printf("Item: %s created!\n", itemName);
    }

    //  Put objectlock retention(i.e. retain until date) on the object.
    public static void putObjectLockRetention(String bucketName,String itemName, AmazonS3 _cosClient)
    {
        LocalDate date = LocalDate.of(2025, 11, 11);
        ObjectLockRetention objRet = new ObjectLockRetention()
                    .withMode("COMPLIANCE")
                    .withRetainUntilDate(date);
        SetObjectRetentionRequest objSet = new SetObjectRetentionRequest()
                    .withBucketName(BUCKET_NAME)
                    .withitemName(itemName)
                    .withRetention(objRet);
                    .withBypassGovernanceRetention(true);
        _cosClient.setObjectRetention(objSet);
        System.out.printf("Successfully added object retention on : %s\n", itemName);
        GetObjectRetentionRequest objReq = new GetObjectRetentionRequest()
            .withBucketName(BUCKET_NAME)
            .withitemName(itemName);
        GetObjectRetentionResult objRes1 = _cosClient.getObjectRetention(objReq);
        ObjectLockRetention objRet1 = objRes1.getRetention();
        System.out.printf("Retention : %s\n", objRet1);
    }

    //  Put objectlock retention(i.e. retain until date) with governance mode on the object.
    public static void putObjectLockRetentionWithGovernanceMode(String bucketName,String itemName, AmazonS3 _cosClient)
    {
        LocalDate date = LocalDate.of(2025, 11, 11);
        ObjectLockRetention objRet = new ObjectLockRetention()
                    .withMode("GOVERNANCE")
                    .withRetainUntilDate(date);
        SetObjectRetentionRequest objSet = new SetObjectRetentionRequest()
                    .withBucketName(BUCKET_NAME)
                    .withitemName(itemName)
                    .withRetention(objRet);
                    .withBypassGovernanceRetention(true);
        _cosClient.setObjectRetention(objSet);
        System.out.printf("Successfully added object retention on : %s\n", itemName);
        GetObjectRetentionRequest objReq = new GetObjectRetentionRequest()
            .withBucketName(BUCKET_NAME)
            .withitemName(itemName);
        GetObjectRetentionResult objRes1 = _cosClient.getObjectRetention(objReq);
        ObjectLockRetention objRet1 = objRes1.getRetention();
        System.out.printf("Retention : %s\n", objRet1);
    }

    // Delete object
    public static void deleteObjectWithBypassGovernance(String bucketName, String itemName) {
        System.out.printf("Deleting item: %s\n", itemName);
        DeleteObjectRequest deleteRequest = new DeleteObjectRequest(BUCKET_NAME, Key)
            .withBypassGovernanceRetention(true);
        _cosClient.deleteObject(deleteRequest);
        System.out.printf("Item: %s deleted!\n", itemName);
    }

}

進行

package main

import (
    "bytes"
    "fmt"
    "time"

    "github.com/IBM/ibm-cos-sdk-go/aws"
    "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
    "github.com/IBM/ibm-cos-sdk-go/aws/session"
    "github.com/IBM/ibm-cos-sdk-go/service/s3"
)

const (
    apiKey            = "<apiKey>"
    serviceInstanceID = "<serviceInstanceID>"
    authEndpoint      = "https://iam.cloud.ibm.com/identity/token"
    serviceEndpoint   = "https://<endpoint>.appdomain.cloud"
)

// Create new bucket with objectlock enabled.
func createBucket(bucketName string, client *s3.S3) {
    createBucketInput := new(s3.CreateBucketInput)
    createBucketInput.Bucket = aws.String(bucketName)
    createBucketInput.ObjectLockEnabledForBucket = aws.Bool(true)
    _, e := client.CreateBucket(createBucketInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Bucket Created !!! ")
    }
}

func uploadObject(bucketName string, client *s3.S3, fileName string, fileContent string) {
    putInput := &s3.PutObjectInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(fileName),
        Body:   bytes.NewReader([]byte(fileContent)),
    }

    _, e := client.PutObject(putInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Uploaded!!! ")
    }
}

func uploadObjectWithGovernanceMode(bucketName string, client *s3.S3, fileName string, fileContent string) {
    retention_date := time.Now().Local().Add(time.Second * 5)
    putInput := &s3.PutObjectInput{
        Bucket:                    aws.String(bucketName),
        Key:                       aws.String(fileName),
        Body:                      bytes.NewReader([]byte(fileContent)),
        ObjectLockMode:            aws.String("GOVERNANCE"),
        ObjectLockRetainUntilDate: aws.Time(retention_date),
    }

    _, e := client.PutObject(putInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Uploaded!!! ")
    }
}

func objectLockConfiguration(bucketName string, client *s3.S3) {
    // Putting default retenion on the COS bucket.
    putObjectLockConfigurationInput := &s3.PutObjectLockConfigurationInput{
        Bucket: aws.String(bucketName),
        ObjectLockConfiguration: &s3.ObjectLockConfiguration{
            ObjectLockEnabled: aws.String(s3.ObjectLockEnabledEnabled),
            Rule: &s3.ObjectLockRule{
                DefaultRetention: &s3.DefaultRetention{
                    Mode: aws.String("COMPLIANCE"),
                    Days: aws.Int64(1),
                },
            },
        },
    }
    _, e := client.PutObjectLockConfiguration(putObjectLockConfigurationInput)

    // Reading the objectlock configuration set on the bucket.
    getObjectLockConfigurationInput := new(s3.GetObjectLockConfigurationInput)
    getObjectLockConfigurationInput.Bucket = aws.String(bucketName)
    response, e := client.GetObjectLockConfiguration(getObjectLockConfigurationInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Configuration =>", response.ObjectLockConfiguration)
    }
}

func objectLockConfigurationwithGovernanceMode(bucketName string, client *s3.S3) {
    // Putting default retenion on the COS bucket.
    putObjectLockConfigurationInput := &s3.PutObjectLockConfigurationInput{
        Bucket: aws.String(bucketName),
        ObjectLockConfiguration: &s3.ObjectLockConfiguration{
            ObjectLockEnabled: aws.String(s3.ObjectLockEnabledEnabled),
            Rule: &s3.ObjectLockRule{
                DefaultRetention: &s3.DefaultRetention{
                    Mode: aws.String("GOVERNANCE"),
                    Days: aws.Int64(1),
                },
            },
        },
    }
    _, e := client.PutObjectLockConfiguration(putObjectLockConfigurationInput)

    // Reading the objectlock configuration set on the bucket.
    getObjectLockConfigurationInput := new(s3.GetObjectLockConfigurationInput)
    getObjectLockConfigurationInput.Bucket = aws.String(bucketName)
    response, e := client.GetObjectLockConfiguration(getObjectLockConfigurationInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Configuration =>", response.ObjectLockConfiguration)
    }
}
func objectLockRetention(bucketName string, client *s3.S3, keyName string) {

    // Put objectlock retenion on the  object uploaded to the bucket.
    retention_date := time.Now().Local().Add(time.Second * 5)
    putObjectRetentionInput := &s3.PutObjectRetentionInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        Retention: &s3.ObjectLockRetention{
            Mode:            aws.String("COMPLIANCE"),
            RetainUntilDate: aws.Time(retention_date),
        },
    }
    _, e := client.PutObjectRetention(putObjectRetentionInput)

    // Get objectlock retention of the above object.
    getObjectRetentionInput := new(s3.GetObjectRetentionInput)
    getObjectRetentionInput.Bucket = aws.String(bucketName)
    getObjectRetentionInput.Key = aws.String(keyName)
    response, e := client.GetObjectRetention(getObjectRetentionInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Retention =>", response.Retention)
    }
}

func objectLockRetentionWithGovernanceMode(bucketName string, client *s3.S3, keyName string) {

    // Put objectlock retenion on the  object uploaded to the bucket.
    retention_date := time.Now().Local().Add(time.Second * 5)
    putObjectRetentionInput := &s3.PutObjectRetentionInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        Retention: &s3.ObjectLockRetention{
            Mode:            aws.String("GOVERNANCE"),
            RetainUntilDate: aws.Time(retention_date),
        },
    }
    _, e := client.PutObjectRetention(putObjectRetentionInput)

    // Get objectlock retention of the above object.
    getObjectRetentionInput := new(s3.GetObjectRetentionInput)
    getObjectRetentionInput.Bucket = aws.String(bucketName)
    getObjectRetentionInput.Key = aws.String(keyName)
    response, e := client.GetObjectRetention(getObjectRetentionInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Retention =>", response.Retention)
    }
}

func objectLocklegalHold(bucketName string, client *s3.S3, keyName string) {

    // Setting the objectlock legal-hold status to ON.
    putObjectlegalHoldInput := &s3.PutObjectlegalHoldInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        legalHold: &s3.ObjectLocklegalHold{
            Status: aws.String("ON"),
        },
    }
    _, e := client.PutObjectlegalHold(putObjectlegalHoldInput)
    // Get objectlock retention of the above object.
    getObjectlegalHoldInput := new(s3.GetObjectlegalHoldInput)
    getObjectlegalHoldInput.Bucket = aws.String(bucketName)
    getObjectlegalHoldInput.Key = aws.String(keyName)
    response, e := client.GetObjectlegalHold(getObjectlegalHoldInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock legal-hold =>", response.legalHold)
    }
}

func deleteObjectWithBypassGovernance(bucketName string, client *s3.S3, fileName string) {
    deleteObjectInput := new(s3.DeleteObjectInput)
    deleteObjectInput.Bucket = aws.String(bucketName)
    deleteObjectInput.Key = aws.String("foo")
    deleteObjectInput.BypassGovernanceRetention = aws.Bool(true)
    _, e := client.DeleteObject(deleteObjectInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Deleted")
    }

}

func main() {

    bucketName := "gocosbucket353"
    textFileName := "go_cos_bucket_file.txt"
    textFileContents := "This is a test file from Node.js code sample!!!"
    conf := aws.NewConfig().
        WithEndpoint(serviceEndpoint).
        WithCredentials(ibmiam.NewStaticCredentials(aws.NewConfig(),
            authEndpoint, apiKey, serviceInstanceID)).
        WithS3ForcePathStyle(true)

    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    createBucket(bucketName, client)                                                   // Create a new cos bucket with object lock enabled.
    objectLockConfiguration(bucketName, client)                                        // Put objectlock configuration(i.e. default retention) on COS bucket and get the configuration.
    objectLockConfigurationwithGovernanceMode(bucketName, client)                      // Put objectlock configuration(i.e. default retention) with governance mode on COS bucket and get the configuration.
    uploadObject(bucketName, client, textFileName, textFileContents)                   // Upload an object to cos bucket.
    uploadObjectWithGovernanceMode(bucketName, client, textFileName, textFileContents) // Upload an object with governance mode to cos bucket.
    objectLockRetention(bucketName, client, textFileName)                              // Put objectlock retention(i.e. retain until date) on the object and get the configured retention.
    objectLockRetentionWithGovernanceMode(bucketName, client, textFileName)            // Put objectlock retention(i.e. retain until date) with governance mode on the object and get the configured retention.
    objectLocklegalHold(bucketName, client, textFileName)                              // Put objectlock legal-hold on the object and get the legal-hold status.
    deleteObjectWithBypassGovernance(bucketName, client, textFileName)                 // Delete object using governace bypass header
}

Terraform

// Create COS instance.
resource "ibm_resource_instance" "cos_instance" {
  name              = "cos-instance"
  resource_group_id = data.ibm_resource_group.cos_group.id
  service           = "cloud-object-storage"
  plan              = "standard"
  location          = "global"
}

// Create a new bucket with objectlock and object versioning enabled.
resource "ibm_cos_bucket" "bucket" {
  bucket_name           = var.bucket_name
  resource_instance_id  = ibm_resource_instance.cos_instance.id
  region_location  = var.regional_loc
  storage_class          = var.standard_storage_class
  object_versioning {
    enable  = true
  }
  object_lock = true
}

// Set object lock configuration on the bucket by providing the crn of the new COS bucket.
resource ibm_cos_bucket_objectlock_configuration "objectlock" {
 bucket_crn      = ibm_cos_bucket.bucket.crn
 bucket_location = var.regional_loc
 object_lock_configuration{
   objectlockenabled = "Enabled"
   objectlockrule{
     defaultretention{
        mode = "COMPLIANCE"
        days = 6
      }
    }
  }
}

// Upload an object to the COS bucket with objectlock retention and objectlock legal-hold.
resource "ibm_cos_bucket_object" "object_object_lock" {
  bucket_crn      = ibm_cos_bucket.bucket.crn
  bucket_location = ibm_cos_bucket.bucket.region_location
  content         = "Hello World 2"
  key             = "plaintext5.txt"
  object_lock_mode              = "COMPLIANCE"
  object_lock_retain_until_date = "2023-02-15T18:00:00Z"
  object_lock_legal_hold_status = "ON"
  force_delete = true
}