Go 사용
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는 최소 1.10에서 최대 1.12의 Go 버전을 필요로 합니다. 이보다 더 높은 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 포털에서 애플리케이션 런타임에 환경 변수를 정의하는 방법에 대한 예를 보여줍니다. apikey
필수 변수는 서비스 자격 증명이 포함된 IBM_API_KEY_ID
, 서비스 자격 증명의 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 클러스터에서 신뢰할 수 있는 프로필 사용을 참조하세요
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
보유, 그리고 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둘 다 환경 변수로 설정할 수 없습니다. 이 중 하나만 설정해야 합니다. 그렇지 않으면 GO sdk가 오류를 처리합니다.
엔드포인트에 대한 자세한 정보는 엔드포인트 및 스토리지 위치를 참조하십시오.
코드 예
새 버킷 작성
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 COS에서는 모든 데이터가 암호화되지만, 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)
}
다음 단계
아직 없는 경우 Go API 문서에서 사용 가능한 자세한 클래스 및 메소드 문서를 참조하십시오.