Go の使用
2027年8月6日にサポート終了となります。 IBM Cloud® Object Storage (COS)SDK( v1 )は、2027年8月6日にサポート終了となります。 この日付以降、アップデート、セキュリティ修正、および新バージョンの提供は終了します。 IBM Cloud Object Storage SDK Go( v2 ) への移行をお勧めします。このSDKでは、パフォーマンスの向上、セキュリティの強化、最新のAPIが提供されており、 IBM による継続的なサポートも受けられます。
IBM Cloud® Object Storage SDK for Go は、IBM Cloud Object Storage を活用するための機能を提供します。
IBM Cloud Object Storage SDK for Go の機能は広範囲にわたり、このガイドの記載範囲とスペースに収まらない機能も多くあります。 クラスやメソッドの詳細なドキュメントについては、 Go API ドキュメントを参照してください。 ソースコードは、 GitHub リポジトリにあります。
SDK の取得
go get を使用して SDK を取得し、GOPATH ワークスペースに追加するか、プロジェクトの Go モジュール依存関係に追加します。 このSDKでは、Goの最小バージョンとして 1.10、最大バージョンとして 1.12 が必要です。 当社の品質管理プロセスが完了次第、Goの将来のバージョンにも対応する予定です。
go get github.com/IBM/ibm-cos-sdk-go
SDK を更新するには、 go get -u を使用して、SDK の最新バージョンを取得してください。
go get -u github.com/IBM/ibm-cos-sdk-go
パッケージのインポート
SDK のインストールが完了したら、以下の例に示すように、SDK を使用するために必要なパッケージを Go アプリケーションにインポートする必要があります。
import (
"github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
"github.com/IBM/ibm-cos-sdk-go/aws"
"github.com/IBM/ibm-cos-sdk-go/aws/session"
"github.com/IBM/ibm-cos-sdk-go/service/s3"
)
クライアントの作成とサービスの認証情報の取得
IBM Cloud Object Storage に接続するために、資格情報 (API キーとサービス・インスタンス ID) を指定することによりクライアントが作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。
資格情報は、サービス資格情報を作成するか、CLI を介して見つけることができます。
図 1 は、IBM Cloud Object Storage ポータルでアプリケーション・ランタイムに環境変数を定義する方法の例を示しています。 必要な変数は、サービス認証情報に含まれる IBM_API_KEY_ID ( apikey )、同じくサービス認証情報に含まれる resource_instance_id を格納した IBM_SERVICE_INSTANCE_ID 、
アカウント適切な値(例: https://iam.cloud.ibm.com/identity/token )が設定された IBM_AUTH_ENDPOINT です。 環境変数を使用してアプリケーション資格情報を定義する場合は、WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). を使用し、構成の例で使用されている類似メソッドを置き換えてください。
AWS S3 からマイグレーションする場合は、~/.aws/credentials から資格情報データを以下の形式で入手することもできます。
[default]
aws_access_key_id = {ACCESS_KEY}
aws_secret_access_key = {SECRET_ACCESS_KEY}
~/.bluemix/cos_credentials と ~/.aws/credentials の両方が存在する場合は、cos_credentials が優先されます。
構成の初期化
// Constants for IBM COS values
const (
apiKey = "<API_KEY>" // eg "0viPHOY7LbLNa9eLftrtHPpTjoGv6hbLD1QalRXikliJ"
serviceInstanceID = "<RESOURCE_INSTANCE_ID>" // eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003xxxxxxxxxx1c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"
authEndpoint = "https://iam.cloud.ibm.com/identity/token"
serviceEndpoint = "<SERVICE_ENDPOINT>" // eg "https://s3.us.cloud-object-storage.appdomain.cloud"
bucketLocation = "<LOCATION>" // eg "us"
)
// Create config
conf := aws.NewConfig().
WithRegion("us-standard").
WithEndpoint(serviceEndpoint).
WithCredentials(ibmiam.NewStaticCredentials(aws.NewConfig(), authEndpoint, apiKey, serviceInstanceID)).
WithS3ForcePathStyle(true)
クライアントを作成し、計算リソースのTrusted Profile認証情報を取得する
クライアントは、サービス認証情報または信頼されたプロファイル認証情報を提供することで作成できる。 このセクションでは を使用してクライアントを作成するための情報を提供します。
IBM Cloud Object Storage に接続するには、クライアントが作成され、信頼されたプロファイル認証情報(信頼されたプロファイル ID と CR トークン・ファイル・パス)を提供することによって構成することもできる。 これらの値は、環境変数から自動的に取得することもできます。
トラステッド・プロファイルを作成し、特定の属性に基づいてコンピュート・リソースとの信頼を確立し、リソースへのアクセス権限を割り当てるためのポリシーを定義するには、 コンピュート・リソースでのアプリのアクセス権限の管理 を参照してください。
Kubernetes クラスタとの信頼関係の確立に関する詳細については、「 Kubernetes および OpenShift クラスタでの信頼済みプロファイルの使用 」を参照してください
GO SDKは、 Kubernetes および OpenShift クラスタでのみ、信頼済みプロファイルを使用した認証をサポートしています。
信頼されたプロファイル認証情報は、アプリケーションの実行時に環境変数として設定することができます。 必要な変数は、信頼済みプロファイル ID trusted profile id を含む TRUSTED_PROFILE_ID 、サービスクレデンシャルの service account token file path を保持する CR_TOKEN_FILE_PATH 、 resource_instance_id を保持する IBM_SERVICE_INSTANCE_ID 、および https://iam.cloud.ibm.com/identity/token のようなアカウント適した値を持つ IBM_AUTH_ENDPOINT である。 環境変数を使用してアプリケーション資格情報を定義する場合は、WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). を使用し、構成の例で使用されている類似メソッドを置き換えてください。
構成の初期化
// Constants for IBM COS values
const (
trustedProfileID = "<TRUSTED_PROFILE_ID>" // eg "Profile-5790481a-8fc5-46a4-bae3-d0e64ff6e0ad"
crTokenFilePath = "<SERVICE_ACCOUNT_TOKEN_FILE_PATH>" // "/var/run/secrets/tokens/service-account-token"
serviceInstanceID = "<RESOURCE_INSTANCE_ID>" // "crn:v1:bluemix:public:cloud-object-storage:global:a/<CREDENTIAL_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
authEndpoint = "https://iam.cloud.ibm.com/identity/token"
serviceEndpoint = "<SERVICE_ENDPOINT>" // eg "https://s3.us.cloud-object-storage.appdomain.cloud"
bucketLocation = "<LOCATION>" // eg "us-standard"
)
// Create config
conf := aws.NewConfig().
WithRegion(bucketLocation).
WithEndpoint(serviceEndpoint).
WithCredentials(ibmiam.NewTrustedProfileCredentialsCR(aws.NewConfig(), authEndpoint, trustedProfileID, crtokenFilePath, serviceInstanceID)).
WithS3ForcePathStyle(true)
API-KeyとTrusted-Profile-IDの両方を環境変数として設定することはできない。 どちらか一方のみを設定してください。 はエラーを投げます。
エンドポイントについて詳しくは、エンドポイントおよびストレージ・ロケーションを参照してください。
クライアントを作成し、サービスID用のTrusted Profile認証情報を取得する
Service IDとTrusted Profileを使用して、 IBM Cloud Object Storage を認証するクライアントを作成できます。 Trusted Profilesは、 IBM Cloud IDが、そのアカウント直接のメンバーシップを必要とせずに、 アカウント内のリソースにアクセスすることを可能にする。 サービスIDをTrusted Profileに関連付けることで、異なる IBM Cloud アカウントまたがるリソースも含め、リソースへのアクセスを安全に許可することができます。 詳細については、 サービスIDのTrusted Profilesの 作成に関する IBM Cloud のドキュメントを参照してください。
開始前に
- ソースアカウントサービスIDを作成する.
- Service IDでAPIキーを作成し、APIキーの値をメモする。
- ターゲットアカウント信頼済みプロファイルを作成し、ソースアカウントサービスIDを関連付ける。 コンソールのサービスIDで信頼を確立するを 参照。 対象 アカウント、アクセスするリソースを含むアカウントである。
- 信頼済みプロファイルに適切なアクセスを割り当てる。
サービスIDと信頼されたプロファイルを使用して認証する
セットアップが完了したら、Go SDKを使用して、サービスIDとTrusted Profileを使用して認証するクライアントを構築します。
-
信頼済みプロファイルIDを使用したクライアントコンフィギュレーションの設定:
package main import ( "fmt" "os" "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 ( serviceInstanceID = "crn-of-target-cos-instance" // eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::" authEndpoint = "https://iam.cloud.ibm.com/identity/token" serviceEndpoint = "cos-endpoint" //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud" trustedProfileId = "" // eg: "Profile-gxxxxx530-xxxx-xxxx-xxxx-abpxxxxb94" serviceIDApiKey = "api-key-of-service-id" ) func TestTrustedProfile func main() { sess := session.Must(session.NewSession()) conf := aws.NewConfig(). WithRegion("us-south"). WithEndpoint(serviceEndpoint). WithCredentials(ibmiam.NewTrustedProfileCredentialsServiceIDWithTrustedProfileId(aws.NewConfig(), authEndpoint, trustedProfileId, serviceIDApiKey, serviceInstanceID)). WithS3ForcePathStyle(true) client := s3.New(sess, conf) } -
信頼済みプロファイル名を使用したクライアントコンフィギュレーションの設定:
package main import ( "fmt" "os" "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 ( serviceInstanceID = "crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::" authEndpoint = "https://iam.cloud.ibm.com/identity/token" serviceEndpoint = "cos-endpoint" //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud" trustedProfileName = "name-of-trusted-profile" accountId = "account-id-that-owns-trusted-profile" serviceIDApiKey = "api-key-of-service-id" ) func TestTrustedProfile func main() { sess := session.Must(session.NewSession()) conf := aws.NewConfig(). WithRegion("us-south"). WithEndpoint(serviceEndpoint). WithCredentials(ibmiam.NewTrustedProfileCredentialsServiceIDWithTrustedProfileName(aws.NewConfig(), authEndpoint, trustedProfileName, accountId, serviceIDApiKey, serviceInstanceID)). WithS3ForcePathStyle(true) client := s3.New(sess, conf) }
信頼済みプロファイル名を使用する場合は、信頼済みプロファイルを所有するアカウント IDも提供する必要があります。
信頼されたプロファイルの資格情報は、実行時に環境変数を通して提供されることもある。
-
信頼されたプロファイルIDで環境変数を使用してクライアントを設定します:
-
ランタイム環境にこれらの環境変数を設定する。
export IBM_SERVICE_INSTANCE_ID="crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::" export TRUSTED_PROFILE_ID="id-of-trusted-profile" export IBM_SERVICE_ID_API_KEY="api-key-of-service-id" export IBM_AUTH_ENDPOINT="https://iam.cloud.ibm.com/identity/token" -
クライアントを構成します。
const ( serviceEndpoint = "cos-endpoint" //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud" ) conf := cltMain().NewConfigNoSSL() conf.WithRegion(cltMain().DefaultRegion()). WithEndpoint(serviceEndpoint). WithS3ForcePathStyle(true) sess := session.Must(session.NewSession()) client := s3.New(sess, conf)
-
-
信頼されたプロファイル名で環境変数を使用してクライアントを設定します:
-
ランタイム環境にこれらの環境変数を設定する。
export IBM_SERVICE_INSTANCE_ID="crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::" export TRUSTED_PROFILE_NAME="name-of-trusted-profile" export IBM_SERVICE_ID_API_KEY="api-key-of-service-id" export IBM_AUTH_ENDPOINT="https://iam.cloud.ibm.com/identity/token" export IAM_ACCOUNT_ID="account-id-owns-trusted-profile" -
クライアントを構成します。
const ( serviceEndpoint = "cos-endpoint" //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud" ) conf := cltMain().NewConfigNoSSL() conf.WithRegion(cltMain().DefaultRegion()). WithEndpoint(serviceEndpoint). WithS3ForcePathStyle(true) sess := session.Must(session.NewSession()) client := s3.New(sess, conf)
-
プレースホルダーの値を実際のCRN、APIキー、プロファイル名またはID、エンドポイント、 アカウント IDに置き換える。
コード例
新規バケットの作成
LocationConstraint の有効なプロビジョニング・コードのリストについては、ストレージ・クラスのガイドを参照してください。
サンプルは、サンプル構成に基づいて、Cold Vaultストレージの適切な場所制約を使用します。 お住まいの地域や構成は異なるかもしれません。
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Names
newBucket := "<NEW_BUCKET_NAME>"
newColdBucket := "<NEW_COLD_BUCKET_NAME>"
input := &s3.CreateBucketInput{
Bucket: aws.String(newBucket),
}
client.CreateBucket(input)
input2 := &s3.CreateBucketInput{
Bucket: aws.String(newColdBucket),
CreateBucketConfiguration: &s3.CreateBucketConfiguration{
LocationConstraint: aws.String("us-cold"),
},
}
client.CreateBucket(input2)
d, _ := client.ListBuckets(&s3.ListBucketsInput{})
fmt.Println(d)
}
使用可能なバケットのリスト
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Call Function
d, _ := client.ListBuckets(&s3.ListBucketsInput{})
fmt.Println(d)
}
オブジェクトをバケットにアップロードします
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Variables and random content to sample, replace when appropriate
bucketName := "<BUCKET_NAME>"
key := "<OBJECT_KEY>"
content := bytes.NewReader([]byte("<CONTENT>"))
input := s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(key),
Body: content,
}
// Call Function to upload (Put) an object
result, _ := client.PutObject(&input)
fmt.Println(result)
}
バケット内のリスト項目(リストオブジェクト V2 )
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Name
Bucket := "<BUCKET_NAME>"
// Call Function
Input := &s3.ListObjectsV2Input{
Bucket: aws.String(Bucket),
}
l, e := client.ListObjectsV2(Input)
fmt.Println(l)
fmt.Println(e) // prints "<nil>"
}
// The response should be formatted like the following example:
//{
// Contents: [{
// ETag: "\"dbxxxxx53xxx7d06378204e3xxxxxx9f\"",
// Key: "file1.json",
// LastModified: 2019-10-15 22:22:52.62 +0000 UTC,
// Size: 1045,
// StorageClass: "STANDARD"
// },{
// ETag: "\"6e1xxxxx63xxxdefb440f72axxxxxxc2\"",
// Key: "file2.json",
// LastModified: 2019-10-15 23:08:10.074 +0000 UTC,
// Size: 1045,
// StorageClass: "STANDARD"
// }],
// Delimiter: "",
// IsTruncated: false,
// KeyCount: 2,
// MaxKeys: 1000,
// Name: "<BUCKET_NAME>",
// Prefix: ""
//}
オブジェクトのコンテンツの取得
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Variables
bucketName := "<NEW_BUCKET_NAME>"
key := "<OBJECT_KEY>"
// users will need to create bucket, key (flat string name)
Input := s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(key),
}
// Call Function
res, _ := client.GetObject(&Input)
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(body)
}
バケットからオブジェクトを削除します
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Name
bucket := "<BUCKET_NAME>"
input := &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: aws.String("<OBJECT_KEY>"),
}
d, _ := client.DeleteObject(input)
fmt.Println(d)
}
バケットから複数オブジェクトを削除
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Name
bucket := "<BUCKET_NAME>"
input := &s3.DeleteObjectsInput{
Bucket: aws.String(bucket),
Delete: &s3.Delete{
Objects: []*s3.ObjectIdentifier{
{
Key: aws.String("<OBJECT_KEY1>"),
},
{
Key: aws.String("<OBJECT_KEY2>"),
},
{
Key: aws.String("<OBJECT_KEY3>"),
},
},
Quiet: aws.Bool(false),
},
}
d, _ := client.DeleteObjects(input)
fmt.Println(d)
}
バケットの削除
func main() {
// Bucket Name
bucket := "<BUCKET_NAME>"
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
input := &s3.DeleteBucketInput{
Bucket: aws.String(bucket),
}
d, _ := client.DeleteBucket(input)
fmt.Println(d)
}
手動の複数パーツ・アップロードの実行
func main() {
// Variables
bucket := "<BUCKET_NAME>"
key := "<OBJECT_KEY>"
content := bytes.NewReader([]byte("<CONTENT>"))
input := s3.CreateMultipartUploadInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
upload, _ := client.CreateMultipartUpload(&input)
uploadPartInput := s3.UploadPartInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
PartNumber: aws.Int64(int64(1)),
UploadId: upload.UploadId,
Body: content,
}
var completedParts []*s3.CompletedPart
completedPart, _ := client.UploadPart(&uploadPartInput)
completedParts = append(completedParts, &s3.CompletedPart{
ETag: completedPart.ETag,
PartNumber: aws.Int64(int64(1)),
})
completeMPUInput := s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: completedParts,
},
UploadId: upload.UploadId,
}
d, _ := client.CompleteMultipartUpload(&completeMPUInput)
fmt.Println(d)
}
Key Protect の使用
暗号鍵を管理するために、Key Protect をストレージ・バケットに追加できます。 IBM Cloud Object Storage ではすべてのデータが暗号化されていますが、 Key Protect では、一元化されたサービスを利用して、暗号化キーの生成、ローテーション、およびアクセス制御を行うサービスを提供しています。
開始前に
Key-Protect を有効にしてバケットを作成するには、以下の項目が必要です:
- プロビジョン済みの Key Protect サービス
- ルートキーが利用可能( 生成 または インポートされたもの)
ルート・キー CRN の取得
- Key Protect サービスのインスタンス ID を取得します。
- Key Protect API を使用して、すべての使用可能なキーを取得します。
curlコマンドまたは API REST クライアント (Postman など) のいずれかを使用して、Key Protect API にアクセスできます。
- バケットで「 Key Protect 」を有効にする際に使用するルートキーのCRNを取得してください。 CRNは次のような形式になっています:
crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234
Key Protect が有効なバケットの作成
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Bucket Names
newBucket := "<NEW_BUCKET_NAME>"
fmt.Println("Creating new encrypted bucket:", newBucket)
input := &s3.CreateBucketInput{
Bucket: aws.String(newBucket),
IBMSSEKPCustomerRootKeyCrn: aws.String("<ROOT-KEY-CRN>"),
IBMSSEKPEncryptionAlgorithm:aws.String("<ALGORITHM>"),
}
client.CreateBucket(input)
// List Buckets
d, _ := client.ListBuckets(&s3.ListBucketsInput{})
fmt.Println(d)
}
キー値
<NEW_BUCKET_NAME>- 新しいバケットの名前。<ROOT-KEY-CRN>- 「 Key Protect 」サービスから取得したルートキーのCRN。<ALGORITHM>- バケットに追加される新しいオブジェクトに対して使用される暗号化アルゴリズム(デフォルトは AES256 )。
Transfer Manager の使用
func main() {
// Variables
bucket := "<BUCKET_NAME>"
key := "<OBJECT_KEY>"
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Create an uploader with S3 client and custom options
uploader := s3manager.NewUploaderWithClient(client, func(u *s3manager.Uploader) {
u.PartSize = 5 * 1024 * 1024 // 64MB per part
})
// make a buffer of 5MB
buffer := make([]byte, 15*1024*1024, 15*1024*1024)
random := rand.New(rand.NewSource(time.Now().Unix()))
random.Read(buffer)
input := &s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: io.ReadSeeker(bytes.NewReader(buffer)),
}
// Perform an upload.
d, _ := uploader.Upload(input)
fmt.Println(d)
// Perform upload with options different than the those in the Uploader.
f, _ := uploader.Upload(input, func(u *s3manager.Uploader) {
u.PartSize = 10 * 1024 * 1024 // 10MB part size
u.LeavePartsOnError = true // Don't delete the parts if the upload fails.
})
fmt.Println(f)
}
拡張リストの取得
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
input := new(s3.ListBucketsExtendedInput).SetMaxKeys(<MAX_KEYS>).SetMarker("<MARKER>").SetPrefix("<PREFIX>")
output, _ := client.ListBucketsExtended(input)
jsonBytes, _ := json.MarshalIndent(output, " ", " ")
fmt.Println(string(jsonBytes))
}
キー値
<MAX_KEYS>- 1回のリクエストで取得できるバケットの最大数。<MARKER>- リスト表示を開始するバケット名(このバケットまではスキップ)。<PREFIX- 名前がこの接頭辞で始まるバケットのみを含めます。
ページ編集付きの拡張リストの取得
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
i := 0
input := new(s3.ListBucketsExtendedInput).SetMaxKeys(<MAX_KEYS>).SetMarker("<MARKER>").SetPrefix("<PREFIX>")
output, _ := client.ListBucketsExtended(input)
for _, bucket := range output.Buckets {
fmt.Println(i, "\t\t", *bucket.Name, "\t\t", *bucket.LocationConstraint, "\t\t", *bucket.CreationDate)
}
}
キー値
<MAX_KEYS>- 1回のリクエストで取得できるバケットの最大数。<MARKER>- リスト表示を開始するバケット名(このバケットまではスキップ)。<PREFIX- 名前がこの接頭辞で始まるバケットのみを含めます。
アーカイブ層のサポート
指定された時間の経過後、または指定された日付の後に、オブジェクトを自動的にアーカイブすることができます。 アーカイブされると、必要に応じてオブジェクトの一時コピーを復元してアクセスすることができます。
1つまたは複数のオブジェクトの一時的なコピーの復元に必要な時間は、最大12時間かかるかもしれない。
提供された例を使うには、 <apikey> やその他の括弧付き <...> 情報を置き換えるなど、独自の設定を行う。ただし、環境変数を使う方がより安全であり、バージョン管理されるコードに認証情報を入れてはならないことに留意すること。
アーカイブ・ポリシーは、クライアント・インスタンスで PutBucketLifecycleConfiguration メソッドを呼び出すことによって、バケット・レベルで設定されます。 新しく追加されたか、変更されたアーカイブ・ポリシーは、アップロードされた新規オブジェクトに適用され、既存のオブジェクトには影響しません。
func main() {
// Create Client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// PUT BUCKET LIFECYCLE CONFIGURATION
// Replace <BUCKET_NAME> with the name of the bucket
lInput := &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String("<BUCKET_NAME>"),
LifecycleConfiguration: &s3.LifecycleConfiguration{
Rules: []*s3.LifecycleRule{
{
Status: aws.String("Enabled"),
Filter: &s3.LifecycleRuleFilter{},
ID: aws.String("id3"),
Transitions: []*s3.Transition{
{
Days: aws.Int64(5),
StorageClass: aws.String("Glacier"),
},
},
},
},
},
}
l, e := client.PutBucketLifecycleConfiguration(lInput)
fmt.Println(l) // should print an empty bracket
fmt.Println(e) // should print <nil>
// GET BUCKET LIFECYCLE CONFIGURATION
gInput := &s3.GetBucketLifecycleConfigurationInput{
Bucket: aws.String("<bucketname>"),
}
g, e := client.GetBucketLifecycleConfiguration(gInput)
fmt.Println(g)
fmt.Println(e) // see response for results
// RESTORE OBJECT
// Replace <OBJECT_KEY> with the appropriate key
rInput := &s3.RestoreObjectInput{
Bucket: aws.String("<BUCKET_NAME>"),
Key: aws.String("<OBJECT_KEY>"),
RestoreRequest: &s3.RestoreRequest{
Days: aws.Int64(100),
GlacierJobParameters: &s3.GlacierJobParameters{
Tier: aws.String("Bulk"),
},
},
}
r, e := client.RestoreObject(rInput)
fmt.Println(r)
fmt.Println(e)
}
典型的な応答の例を以下に示します。
{
Rules: [{
Filter: {
},
ID: "id3",
Status: "Enabled",
Transitions: [{
Days: 5,
StorageClass: "GLACIER"
}]
}]
}
Immutable Object Storage
ユーザは、Immutable Object Storage ポリシーでバケットを設定し、オブジェクトが定義された期間変更または削除されないようにすることができます。 保存期間は、オブジェクトごとに指定することも、オブジェクトがバケットに設定されたデフォルトの保存期間を継承することもできます。 また、無制限の永久保存期間を設定することもできます。 不変の Object Storage は、レコード保存を管理する SEC によって規定された規則を満たしているため、 IBM Cloud 管理者はこれらの制限をバイパスできません。
Immutable Object Storage は、現段階では、オブジェクトやディレクトリをアップロードするためのSDKを介した Aspera 転送をサポートしていません。
func main() {
// Create Client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Create a bucket
input := &s3.CreateBucketInput{
Bucket: aws.String("<BUCKET_NAME>"),
}
d, e := client.CreateBucket(input)
fmt.Println(d) // should print an empty bracket
fmt.Println(e) // should print <nil>
// PUT BUCKET PROTECTION CONFIGURATION
pInput := &s3.PutBucketProtectionConfigurationInput{
Bucket: aws.String("<BUCKET_NAME>"),
ProtectionConfiguration: &s3.ProtectionConfiguration{
DefaultRetention: &s3.BucketProtectionDefaultRetention{
Days: aws.Int64(100),
},
MaximumRetention: &s3.BucketProtectionMaximumRetention{
Days: aws.Int64(1000),
},
MinimumRetention: &s3.BucketProtectionMinimumRetention{
Days: aws.Int64(10),
},
Status: aws.String("Retention"),
},
}
p, e := client.PutBucketProtectionConfiguration(pInput)
fmt.Println(p)
fmt.Println(e) // see response for results
// GET BUCKET PROTECTION CONFIGURATION
gInput := &s3.GetBucketProtectionConfigurationInput{
Bucket: aws.String("<BUCKET_NAME>"),
}
g, e := client.GetBucketProtectionConfiguration(gInput)
fmt.Println(g)
fmt.Println(e)
}
典型的な応答の例を以下に示します。
{
ProtectionConfiguration: {
DefaultRetention: {
Days: 100
},
MaximumRetention: {
Days: 1000
},
MinimumRetention: {
Days: 10
},
Status: "COMPLIANCE"
}
}
ホストされた静的 Web サイトの作成
通常、バケット所有者のみが静的 Web サイトをホストするようにバケットを構成することを許可されるため、この操作には許可が必要です。 これらのパラメーターは、サイトへの訪問者のデフォルトの接尾部と、例を完成させるためにここに示すオプションのエラー文書を決定します。
func main() {
// Create Client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Create a bucket
input := &s3.CreateBucketInput{
Bucket: aws.String("<BUCKET_NAME>"),
}
d, e := client.CreateBucket(input)
fmt.Println(d) // should print an empty bracket
fmt.Println(e) // should print <nil>
// PUT BUCKET WEBSITE
pInput := s3.PutBucketWebsiteInput{
Bucket: input,
WebsiteConfiguration: &s3.WebsiteConfiguration{
IndexDocument: &s3.IndexDocument{
Suffix: aws.String("index.html"),
},
},
}
pInput.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{
Key: aws.String("error.html"),
}
p, e := client.PutBucketWebsite(¶ms)
fmt.Println(p)
fmt.Println(e) // see response for results
}
バックアップ・ポリシーの作成
func main() {
apiKey := "<API_KEY>"
policyName := "<POLICY_NAME>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
backupVaultCrn := "<BACKUP_VAULT_CRN>"
// Initialize authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize ResourceConfiguration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Create Backup Policy
// Define initial retention
initialRetention := &resourceconfigurationv1.DeleteAfterDays{
DeleteAfterDays: core.Int64Ptr(1),
}
// Create backup policy
createBackupPolicyOptions := &resourceconfigurationv1.CreateBackupPolicyOptions{
Bucket: core.StringPtr(sourceBucketName),
PolicyName: core.StringPtr(policyName),
TargetBackupVaultCrn: core.StringPtr(backupVaultCrn),
BackupType: core.StringPtr("continuous"),
InitialRetention: initialRetention,
}
createResponse, _, err := rcClient.CreateBackupPolicy(createBackupPolicyOptions)
if err != nil {
log.Fatalf("Failed to create backup policy: %v", err)
}
fmt.Println("Backup policy created:")
fmt.Println(createResponse)
}
バックアップ・ポリシーのリスト
func main() {
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
// Initialize IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize ResourceConfiguration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// List all backup policies
listBackupPoliciesOptions := &resourceconfigurationv1.ListBackupPoliciesOptions{
Bucket: core.StringPtr(sourceBucketName),
}
result, _, err := rcClient.ListBackupPolicies(listBackupPoliciesOptions)
if err != nil {
log.Fatalf("Failed to list backup policies: %v", err)
}
fmt.Println(result.BackupPolicies)
}
バックアップ・ポリシー
func main() {
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
policyId := "<POLICY_ID>"
// Initialize IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize ResourceConfiguration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Fetch backup policy using policy ID
getBackupPolicyOptions := &resourceconfigurationv1.GetBackupPolicyOptions{
Bucket: core.StringPtr(sourceBucketName),
PolicyID: core.StringPtr(policyId),
}
getResponse, _, err := rcClient.GetBackupPolicy(getBackupPolicyOptions)
if err != nil {
log.Fatalf("Failed to fetch backup policy: %v", err)
}
fmt.Println("\nFetched Backup Policy Details:")
fmt.Println(getResponse)
}
バックアップポリシーの削除
func main() {
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
backupVaultCrn := "<BACKUP_VAULT_CRN>"
policyId := "<POLICY_ID>"
// Initialize IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize ResourceConfiguration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Delete the created backup policy
deleteBackupPolicyOptions := &resourceconfigurationv1.DeleteBackupPolicyOptions{
Bucket: core.StringPtr(sourceBucketName),
PolicyID: core.StringPtr(policyId),
}
_, err = rcClient.DeleteBackupPolicy(deleteBackupPolicyOptions)
if err != nil {
log.Fatalf("Failed to delete backup policy: %v", err)
}
fmt.Printf("Backup policy '%s' deleted successfully.\n", policyId)
}
バックアップ保管庫の作成
func main() {
apiKey := "<API_KEY>"
serviceInstanceID := "<SERVICE_INSTANCE_ID>"
region := "<REGION>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Create backup vault
createBackupVaultOptions := &resourceconfigurationv1.CreateBackupVaultOptions{
ServiceInstanceID: core.StringPtr(serviceInstanceID),
BackupVaultName: core.StringPtr(backupVaultName),
Region: core.StringPtr(region),
}
createResponse, _, err := rcClient.CreateBackupVault(createBackupVaultOptions)
if err != nil {
log.Fatalf("Failed to create backup vault: %v", err)
}
fmt.Printf(createResponse)
}
バックアップ保管庫のリストアップ
func main() {
apiKey := "<API_KEY>"
serviceInstanceID := "<SERVICE_INSTANCE_ID>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// List backup vaults
listBackupVaultsOptions := &resourceconfigurationv1.ListBackupVaultsOptions{
ServiceInstanceID: core.StringPtr(serviceInstanceID),
}
result, _, err := rcClient.ListBackupVaults(listBackupVaultsOptions)
if err != nil {
log.Fatalf("Failed to list backup vaults: %v", err)
}
fmt.Println(result.BackupVaults)
}
バックアップ保管庫の取得
func main() {
apiKey := "<API_KEY>"
serviceInstanceID := "<SERVICE_INSTANCE_ID>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Get backup vault details
getBackupVaultOptions := &resourceconfigurationv1.GetBackupVaultOptions{
BackupVaultName: core.StringPtr(backupVaultName),
}
result, _, err := rcClient.GetBackupVault(getBackupVaultOptions)
if err != nil {
log.Fatalf("Failed to get backup vault details: %v", err)
}
fmt.Println(result.GetBackupVault)
}
バックアップ保管庫の更新
func main() {
apiKey := "<API_KEY>"
serviceInstanceID := "<SERVICE_INSTANCE_ID>"
region := "<REGION>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Update backup vault: disable activity tracking and metrics monitoring
backupVaultPatch := &resourceconfigurationv1.BackupVaultPatch{
ActivityTracking: &resourceconfigurationv1.BackupVaultActivityTracking{
ManagementEvents: core.BoolPtr(false),
},
MetricsMonitoring: &resourceconfigurationv1.BackupVaultMetricsMonitoring{
UsageMetricsEnabled: core.BoolPtr(false),
},
}
bucketPatchModelAsPatch, _ := backupVaultPatch.AsPatch()
updateBucketBackupVaultOptions := &resourceconfigurationv1.UpdateBackupVaultOptions{
BackupVaultName: core.StringPtr(backupVaultName),
BackupVaultPatch: bucketPatchModelAsPatch,
}
_, patchResponse, err := rcClient.UpdateBackupVault(updateBucketBackupVaultOptions)
if err != nil {
log.Fatalf("Failed to update backup vault: %v", err)
}
fmt.Println(patchResponse)
}
バックアップ保管庫の削除
func main() {
apiKey := "<API_KEY>"
serviceInstanceID := "<SERVICE_INSTANCE_ID>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Delete backup vault
deleteBackupVaultOptions := &resourceconfigurationv1.DeleteBackupVaultOptions{
BackupVaultName: core.StringPtr(backupVaultName),
}
_, err = rcClient.DeleteBackupVault(deleteBackupVaultOptions)
if err != nil {
log.Fatalf("Failed to delete backup vault: %v", err)
}
}
リスト回復範囲
func main() {
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
backupVaultCrn := "<BACKUP_VAULT_CRN>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// List recovery ranges
listRecoveryRangesOptions := &resourceconfigurationv1.ListRecoveryRangesOptions{
BackupVaultName: core.StringPtr(backupVaultName),
}
recoveryRangesResponse, _, err := rcClient.ListRecoveryRanges(listRecoveryRangesOptions)
if err != nil {
log.Fatalf("Failed to list recovery ranges: %v", err)
}
fmt.Println(recoveryRangesResponse)
}
回復範囲を得る
func main() {
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
backupVaultCrn := "<BACKUP_VAULT_CRN>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Fetch details of the recovery range
getRecoveryRangeOptions := &resourceconfigurationv1.GetSourceResourceRecoveryRangeOptions{
BackupVaultName: core.StringPtr(backupVaultName),
RecoveryRangeID: core.StringPtr(recoveryRangeId),
}
getRecoveryRangeResponse, _, err := rcClient.GetSourceResourceRecoveryRange(getRecoveryRangeOptions)
if err != nil {
log.Fatalf("Failed to fetch recovery range: %v", err)
}
fmt.Println(recoveryRangesResponse)
}
回復範囲の更新
func main() {
// Config values
apiKey := "<API_KEY>"
sourceBucketName := "<SOURCE_BUCKET_NAME>"
backupVaultCRN := "<BACKUP_VAULT_CRN>"
backupVaultName := "<BACKUP_VAULT_NAME>"
// Setup IAM Authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
options := &resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
}
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1UsingExternalConfig(options)
if err != nil {
log.Fatalf("Failed to create Resource Configuration client: %v", err)
}
// Patch the recovery range (update retention to 99 days)
patchOpts := &resourceconfigurationv1.PatchSourceResourceRecoveryRangeOptions{
BackupVaultName: core.StringPtr(backupVaultName),
RecoveryRangeID: core.StringPtr(recoveryRangeID),
RecoveryRangePatch: &resourceconfigurationv1.RecoveryRangePatch{
Retention: &resourceconfigurationv1.DeleteAfterDays{
DeleteAfterDays: core.Int64Ptr(99),
},
},
}
patchResp, _, err := rcClient.PatchSourceResourceRecoveryRange(patchOpts)
if err != nil {
log.Fatalf("Failed to patch recovery range: %v", err)
}
fmt.Println("Successfully patched recovery range:")
fmt.Printf("%+v\n", patchResp)
}
リストアの開始
func main() {
// Setup authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Initiate restore
restoreOptions := &resourceconfigurationv1.CreateRestoreOptions{
BackupVaultName: core.StringPtr(backupVaultName),
RecoveryRangeID: core.StringPtr(recoveryRangeId),
RestoreType: core.StringPtr("in_place"),
RestorePointInTime: core.StringPtr(restorePointInTime),
TargetResourceCrn: core.StringPtr(targetBucketCrn),
}
restoreResponse, _, err := rcClient.CreateRestore(restoreOptions)
if err != nil {
log.Fatalf("Failed to initiate restore: %v", err)
}
fmt.Printf(restoreResponse)
}
リストア
func main() {
// Setup authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// List restores
listOptions := &resourceconfigurationv1.ListRestoresOptions{
BackupVaultName: core.StringPtr(backupVaultName),
}
restoreListResponse, _, err := rcClient.ListRestores(listOptions)
if err != nil {
log.Fatalf("Failed to list restore operations: %v", err)
}
fmt.Printf(restoreListResponse)
}
リストアの詳細
func main() {
// Setup authenticator
authenticator := &core.IamAuthenticator{
ApiKey: apiKey,
}
// Initialize Resource Configuration client
rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
Authenticator: authenticator,
})
if err != nil {
log.Fatalf("Failed to create RC client: %v", err)
}
// Get specific restore
restoreGetOptions := &resourceconfigurationv1.GetRestoreOptions{
BackupVaultName: core.StringPtr(backupVaultName),
RestoreID: core.StringPtr(restoreId),
}
restoreDetails, _, err := rcClient.GetRestore(restoreGetOptions)
if err != nil {
log.Fatalf("Failed to get restore details: %v", err)
}
fmt.Printf("Restore details: %+v\n", restoreDetails)
}
オブジェクトロックを有効にして、新しい Cloud Object Storage バケツを作成する
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 !!! ")
}
}
Cloud Object Storage バケットにコンプライアンス・モードでオブジェクト・ロックの設定を入れる
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)
}
Cloud Object Storage バケットにガバナンス・モードでオブジェクト・ロックの設定を入れる
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)
}
Cloud Object Storage バケットのオブジェクトロック設定を取得する
func objectLockConfigurationwithGovernanceMode(bucketName string, client *s3.S3) {
// 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)
}
}
Cloud Object Storage バケットにガバナンスモードのオブジェクトをアップロードする
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 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)
}
オブジェクトにガバナンスモードのオブジェクトロック保持を設定する
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)
}
オブジェクトロックの保持を取得する
func objectLockRetentionWithGovernanceMode(bucketName string, client *s3.S3, keyName string) {
// 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)
}
オブジェクトロックの法的保持を取得する
func objectLocklegalHold(bucketName string, client *s3.S3, keyName string) {
// 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")
}
}
次のステップ
まだの方は、 Go APIドキュメントにある詳細なクラスとメソッドのドキュメントをご覧ください。