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를 최대한 활용할 수 있는 기능을 제공합니다.
The 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 포털에서 애플리케이션 런타임에 환경 변수를 정의하는 방법에 대한 예를 보여줍니다. 필요한 변수로는 서비스 자격 증명(Service Credential)에 포함된 ‘ 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)
클라이언트 만들기 및 컴퓨팅 리소스에 대한 신뢰할 수 있는 프로필 자격 증명 소싱하기
서비스 자격 증명 또는 신뢰할 수 있는 프로필 자격 증명을 제공하여 클라이언트를 만들 수 있습니다. 이 섹션에서는 다음과 같은 정보를 제공합니다 신뢰할 수 있는 프로필 자격 증명을 사용하여 클라이언트를 만드는 방법에 대한 정보를 제공합니다.
IBM Cloud Object Storage 에 연결하려면 클라이언트가 생성되며, 신뢰할 수 있는 프로필 자격 증명 정보(신뢰할 수 있는 프로필 ID 및 CR 토큰 파일 경로)를 제공하여 구성할 수도 있습니다. 이러한 값은 환경 변수에서 자동으로 소싱될 수도 있습니다.
신뢰할 수 있는 프로파일을 작성하여 특정 속성을 기반으로 하는 컴퓨팅 리소스를 사용하여 신뢰를 설정하고 리소스에 대한 액세스를 지정하는 정책을 정의하려면 컴퓨팅 리소스에서 앱에 대한 액세스 관리 를 참조하십시오.
Kubernetes 클러스터와의 신뢰 관계 설정에 대해 자세히 알아보려면 다음을 참조하십시오. Kubernetes 및 OpenShift 클러스터에서 Trusted Profiles 사용
GO SDK는 Kubernetes 및 OpenShift 클러스터에서만 신뢰할 수 있는 프로필을 사용한 인증을 지원합니다.
신뢰할 수 있는 프로필 자격 증명은 애플리케이션 런타임 중에 환경 변수로 설정할 수 있습니다. 필수 변수는 TRUSTED_PROFILE_ID 에 신뢰할 수 있는 프로필 ID trusted profile id, CR_TOKEN_FILE_PATH 에 service account token file path, IBM_SERVICE_INSTANCE_ID 에 서비스 자격증명에서 resource_instance_id, 그리고 IBM_AUTH_ENDPOINT 에 https://iam.cloud.ibm.com/identity/token 과 같이 계정에 적합한 값입니다. 환경 변수를 사용하여 애플리케이션 인증 정보를 정의하는 경우에는 구성 예에서 사용된 유사한 메소드를 대체하여 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는 모두 환경 변수로 설정할 수 없습니다. 이 중 하나만 설정해야 하며, 그렇지 않으면 GO SDK 가 오류를 발생시킵니다.
엔드포인트에 대한 자세한 정보는 엔드포인트 및 스토리지 위치를 참조하십시오.
클라이언트 만들기 및 서비스 ID에 대한 신뢰할 수 있는 프로필 자격 증명 소싱하기
이제 신뢰할 수 있는 프로필과 함께 서비스 ID를 사용하여 IBM Cloud Object Storage 로 인증하는 클라이언트를 만들 수 있습니다. 신뢰할 수 있는 프로필을 사용하면 IBM Cloud ID가 해당 계정에 직접 가입하지 않고도 계정의 리소스에 액세스할 수 있습니다. 서비스 ID를 신뢰할 수 있는 프로필과 연결하면 다른 IBM Cloud 계정에 있는 리소스를 포함한 리소스에 대한 액세스 권한을 안전하게 부여할 수 있습니다. 자세한 내용은 서비스 ID에 대한 신뢰할 수 있는 프로필 만들기에 대한 IBM Cloud 문서를 참조하세요.
시작하기 전에
- 소스 계정에서 서비스 ID를 만듭니다.
- 서비스 ID에서 API 키를 생성하고 API 키 값을 기록합니다.
- 대상 계정에서 신뢰할 수 있는 프로필을 만들고 소스 계정의 서비스 ID를 연결합니다. 콘솔에서 서비스 ID로 신뢰 설정하기를 참조하세요. 대상 계정은 액세스하려는 리소스가 포함된 계정입니다.
- 신뢰할 수 있는 프로필에 적절한 액세스 권한을 할당합니다.
서비스 ID와 신뢰할 수 있는 프로필을 사용하여 인증하기
설정이 완료되면 Go SDK를 사용하여 서비스 ID와 신뢰할 수 있는 프로필을 사용하여 인증하는 클라이언트를 빌드합니다.
-
신뢰할 수 있는 프로필 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에 대한 올바른 프로비저닝 코드 목록은 스토리지 클래스 안내서에서 참조할 수 있습니다.
이 샘플은 샘플 구성에 따라 콜드 볼트 스토리지에 적절한 위치 제약 조건을 사용합니다. 위치 및 구성은 다를 수 있습니다.
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가 활성화된 버킷을 생성하려면 다음 항목이 필요합니다:
루트 키 CRN 검색
- Key Protect 서비스의 인스턴스 ID를 검색하십시오.
- Key Protect API를 사용하여 사용 가능한 키를 모두 검색하십시오.
curl명령을 사용하거나 Postman과 같은 API REST 클라이언트를 사용하여 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 입니다).
전송 관리자 사용
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>- 요청에서 가져올 버킷의 최대 개수.<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>- 요청에서 가져올 버킷의 최대 개수.<MARKER>- 목록을 시작할 버킷 이름(이 버킷까지 건너뛰기).<PREFIX- 이름이 이 접두사로 시작하는 버킷만 포함합니다.
아카이브 티어 지원
지정된 시간 이후 또는 지정된 날짜 이후에 자동으로 오브젝트를 아카이브할 수 있습니다. 아카이브되면 필요에 따라 액세스를 위해 오브젝트의 임시 사본을 복원할 수 있습니다.
하나 이상의 개체의 임시 사본을 복원하는 데 필요한 시간은 최대 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"
}]
}]
}
불변 오브젝트 스토리지
사용자는 변경 불가 Object Storage 정책으로 버킷을 구성하여 정해진 기간 동안 개체가 수정되거나 삭제되지 않도록 할 수 있습니다. 보존 기간은 오브젝트별로 지정하거나 오브젝트는 버킷에 설정된 기본 보존 기간을 상속할 수 있습니다. 개방형 및 영구 보존 기간을 설정할 수도 있습니다. 불변 Object Storage 는 SEC 관리 레코드 보존에 의해 설정된 규칙을 충족하며 IBM Cloud 관리자는 이러한 제한사항을 무시할 수 없습니다.
불변 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"
}
}
호스팅된 정적 웹 사이트 작성
일반적으로 버킷 소유자만 정적 웹 사이트를 호스트하도록 버킷을 구성할 수 있으므로 이 조작에는 권한이 필요합니다. 매개변수는 사이트 방문자의 기본 접미부와 여기에 포함된 선택적 오류 문서를 결정하여 예제를 완료합니다.
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 문서에서 자세한 클래스 및 메서드 설명서를 참조하세요.