Usando Go
Fim do suporte em 6 de agosto de 2027. O SDK do COS ( IBM Cloud® Object Storage ) v1 chegará ao fim do suporte em 6 de agosto de 2027. Após essa data, ele não receberá mais atualizações, correções de segurança nem novas versões. Recomendamos a migração para o SDK Go do IBM Cloud Object Storage v2, que oferece melhor desempenho, segurança aprimorada, APIs modernas e suporte contínuo em IBM.
O IBM Cloud® Object Storage SDK for Go fornece recursos para aproveitar ao máximo o IBM Cloud Object Storage.
O IBM Cloud Object Storage SDK for Go é abrangente, com muitas capacidades e recursos que excedem o escopo e o espaço deste guia. Para obter documentação detalhada sobre classes e métodos, consulte a documentação da API do Go. O código-fonte pode ser encontrado no repositório GitHub.
Obtendo o SDK
Use go get para recuperar o SDK para incluí-lo em sua área de trabalho GOPATH ou nas dependências do módulo Go do projeto. O SDK requer uma versão mínima do Go 1.10 e uma versão máxima do Go 1.12. As versões futuras do Go deverão
ser compatíveis assim que nosso processo de controle de qualidade for concluído.
go get github.com/IBM/ibm-cos-sdk-go
Para atualizar o SDK, acesse go get -u para baixar a versão mais recente do SDK.
go get -u github.com/IBM/ibm-cos-sdk-go
Importar pacotes
Depois de ter instalado o SDK, será necessário importar os pacotes que você requer em seus aplicativos Go para usar o SDK, conforme mostrado no exemplo a seguir:
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"
)
Criação de um cliente e obtenção das credenciais do serviço
Para se conectar ao IBM Cloud Object Storage, um cliente é criado e configurado fornecendo informações de credenciais (Chave de API e ID da instância de serviço). Esses valores também podem ser originados automaticamente de um arquivo de credenciais ou de variáveis de ambiente.
As credenciais podem ser localizadas criando uma Credencial de serviço ou por meio da CLI.
A Figura 1 mostra um exemplo de como definir variáveis de ambiente em um tempo de execução do aplicativo no portal do IBM Cloud Object Storage. As variáveis necessárias são: IBM_API_KEY_ID , que contém sua credencial
de serviço apikey; ` `IBM_SERVICE_INSTANCE_ID` `, que contém o ` `resource_instance_id` `, também proveniente da sua credencial de serviço; e ` `IBM_AUTH_ENDPOINT` `, com um valor adequado à sua conta, como ` `https://iam.cloud.ibm.com/identity/token.
Se for usar variáveis de ambiente para definir suas credenciais do aplicativo, use WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig()))., substituindo o método semelhante usado no exemplo de configuração.
variáveis de ambiente
Se estiver migrando do AWS S3, também será possível originar os dados de credenciais de ~/.aws/credentials no formato:
[default]
aws_access_key_id = {ACCESS_KEY}
aws_secret_access_key = {SECRET_ACCESS_KEY}
Se ambos, ~/.bluemix/cos_credentials e ~/.aws/credentials, existirem, cos_credentials terá a preferência.
Inicializando a configuração
// 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)
Criação de um cliente e obtenção de credenciais de Perfil Confiável para Recursos Computadorizados
Um cliente pode ser criado fornecendo credenciais de serviço ou credenciais de perfil confiável. Esta seção fornece informações para criar um cliente usando credenciais de perfil confiáveis.
Para se conectar a IBM Cloud Object Storage, um cliente é criado e também pode ser configurado fornecendo informações de credenciais de perfil confiável (ID do perfil confiável e caminho do arquivo do token CR). Esses valores também podem ser originados automaticamente de variáveis de ambiente.
Para criar um Perfil Confiável, estabelecendo confiança com recursos de cálculo com base em atributos específicos e para definir uma política para designar acesso a recursos, consulte Gerenciando o acesso para apps em recursos de computação
Para saber mais sobre como estabelecer confiança com um cluster do Kubernetes, consulte “Usando perfis confiáveis em seus clusters do Kubernetes e do OpenShift ”
O GO SDK oferece suporte à autenticação usando o perfil confiável somente nos clusters Kubernetes e OpenShift.
As credenciais de perfil confiáveis podem ser definidas como variáveis de ambiente durante o tempo de execução do aplicativo. As variáveis necessárias são TRUSTED_PROFILE_ID contendo seu ID de perfil confiável trusted profile id,
CR_TOKEN_FILE_PATH contendo o service account token file path, IBM_SERVICE_INSTANCE_ID contendo o resource_instance_id de sua credencial de serviço e um IBM_AUTH_ENDPOINT com
um valor apropriado para sua conta, como https://iam.cloud.ibm.com/identity/token. Se for usar variáveis de ambiente para definir suas credenciais do aplicativo, use WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())).,
substituindo o método semelhante usado no exemplo de configuração.
Inicializando a configuração
// 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)
Tanto a API-Key quanto o Trusted-Profile-ID não podem ser definidos como variáveis de ambiente. Apenas um deles deve ser definido, caso contrário, o GO SDK gera um erro.
Para obter mais informações sobre terminais, consulte Terminais e locais de armazenamento.
Criação de um cliente e obtenção de credenciais de perfil confiável para a ID de serviço
Agora você pode criar um cliente que se autentica em IBM Cloud Object Storage usando uma ID de serviço junto com um Trusted Profile. Os perfis confiáveis permitem que as identidades IBM Cloud acessem recursos em uma conta sem precisar de associação direta a essa conta. Ao associar um Service ID a um Trusted Profile, você pode conceder a ele acesso seguro a recursos, incluindo aqueles localizados em diferentes contas IBM Cloud. Para obter mais detalhes, consulte a documentação IBM Cloud sobre a criação de perfis confiáveis para IDs de serviço.
Antes de Iniciar
- Crie uma ID de serviço na conta de origem.
- Na ID do serviço, crie uma chave de API e anote o valor da chave de API.
- Crie um perfil confiável na conta de destino e associe a ID de serviço da conta de origem. Consulte Estabelecimento de confiança com IDs de serviço no console. A conta de destino é a conta que contém os recursos a serem acessados.
- Atribua o acesso adequado ao perfil confiável.
Autenticar usando a ID do serviço e o perfil confiável
Quando a configuração estiver concluída, use o Go SDK para criar um cliente que se autentique usando a ID do serviço e o perfil confiável.
-
Definição da configuração do cliente usando o ID do perfil confiável:
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) } -
Definir a configuração do cliente usando o nome do perfil confiável:
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) }
Ao usar o nome do Trusted Profile, você também deve fornecer o ID da conta que possui o Trusted Profile.
As credenciais de perfil confiável também podem ser fornecidas por meio de variáveis de ambiente em tempo de execução.
-
Configuração do cliente usando variáveis de ambiente com ID de perfil confiável:
-
Defina essas variáveis de ambiente em seu ambiente de tempo de execução.
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" -
Configure o cliente.
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)
-
-
Configuração do cliente usando variáveis de ambiente com o nome do perfil confiável:
-
Defina essas variáveis de ambiente em seu ambiente de tempo de execução.
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" -
Configure o cliente.
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)
-
Substitua os valores de espaço reservado por CRNs, chaves de API, nomes ou IDs de perfil, pontos de extremidade e IDs de conta reais.
Exemplos de código
Criando um novo depósito
Uma lista de códigos de fornecimento válidos para LocationConstraint pode ser referenciada no guia de Classes de armazenamento.
A amostra usa a restrição de local apropriada para o armazenamento do Cold Vault com base na configuração da amostra. Seus locais e configurações podem variar.
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)
}
Listar depósitos disponíveis
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Call Function
d, _ := client.ListBuckets(&s3.ListBucketsInput{})
fmt.Println(d)
}
Fazer upload de um objeto em um depósito
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)
}
Itens da lista em um bucket (Objetos de lista 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: ""
//}
Obter conteúdo de um objeto
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)
}
Excluir um objeto de um depósito
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)
}
Excluir múltiplos objetos de um depósito
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)
}
Excluir um depósito
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)
}
Executar um upload manual de múltiplas partes
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)
}
Usando o Key Protect
O Key Protect pode ser incluído em um depósito de armazenamento para gerenciar chaves de criptografia. Todos os dados são criptografados no IBM Cloud Object Storage, mas o Key Protect oferece um serviço para gerar, alternar e controlar o acesso às chaves de criptografia por meio de um serviço centralizado.
Antes de iniciar
Os itens a seguir são necessários para criar um bucket com o Key-Protect ativado:
- Um serviço Key Protect provisionado
- Uma chave raiz está disponível ( gerada ou importada )
Recuperando o CRN da chave raiz
- Recupere o ID da instância para seu serviço Key Protect
- Use a API do Key Protect para recuperar todas as suas chaves disponíveis
- É possível usar comandos
curlou um Cliente REST de API, como Postman, para acessar a API do Key Protect.
- É possível usar comandos
- Recupere o CRN da chave raiz que você usa para habilitar o recurso “ Key Protect ” no seu bucket. O CRN tem uma aparência semelhante à seguinte:
crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234
Criando um depósito com o Key Protect ativado
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)
}
Valores da chave
<NEW_BUCKET_NAME>- O nome do novo bucket.<ROOT-KEY-CRN>- CRN da chave raiz obtida no serviço Key Protect.<ALGORITHM>- O algoritmo de criptografia utilizado para novos objetos adicionados ao bucket (o padrão é AES256 ).
Usar o gerenciador de transferência
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)
}
Obtendo uma listagem ampliada
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))
}
Valores da chave
<MAX_KEYS>- Número máximo de buckets a serem recuperados na solicitação.<MARKER>- O nome do bucket a partir do qual a lista deve começar (pular até esse bucket).<PREFIX- Inclua apenas buckets cujo nome comece com esse prefixo.
Obtendo uma listagem ampliada com paginação
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)
}
}
Valores da chave
<MAX_KEYS>- Número máximo de buckets a serem recuperados na solicitação.<MARKER>- O nome do bucket a partir do qual a lista deve começar (pular até esse bucket).<PREFIX- Inclua apenas buckets cujo nome comece com esse prefixo.
Suporte da camada de archive
É possível arquivar objetos automaticamente após um período especificado ou após uma data especificada. Depois de arquivado, uma cópia temporária de um objeto pode ser restaurada para acesso, conforme necessário
O tempo necessário para restaurar a cópia temporária de um ou mais objetos pode levar até 12 horas.
Para usar o exemplo fornecido, forneça sua própria configuração, incluindo a substituição de <apikey> e outras informações entre colchetes de <...>, tendo em mente que o uso de variáveis de ambiente é
mais seguro e que você não deve colocar credenciais em códigos que serão versionados.
Uma política de archive é configurada no nível do depósito, chamando o método PutBucketLifecycleConfiguration em uma instância do cliente Uma política de archive recém-incluída ou modificada aplica-se a novos objetos transferidos
por upload e não afeta objetos existentes.
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)
}
A resposta típica é exemplificada aqui.
{
Rules: [{
Filter: {
},
ID: "id3",
Status: "Enabled",
Transitions: [{
Days: 5,
StorageClass: "GLACIER"
}]
}]
}
Immutable Object Storage
Os usuários podem configurar buckets com uma política Immutable Object Storage para impedir que os objetos sejam modificados ou excluídos por um período definido. O período de retenção pode ser especificado por objeto ou os objetos podem herdar um período de retenção padrão configurado no depósito. Também é possível definir períodos de retenção ilimitada e permanente. O imutável Object Storage atende às regras estabelecidas pelo SEC que controlam a retenção de registro e os administradores do IBM Cloud não podem ignorar essas restrições
O Immutable Object Storage não oferece suporte a transferências Aspera por meio do SDK para carregar objetos ou diretórios neste estágio.
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)
}
A resposta típica é exemplificada aqui.
{
ProtectionConfiguration: {
DefaultRetention: {
Days: 100
},
MaximumRetention: {
Days: 1000
},
MinimumRetention: {
Days: 10
},
Status: "COMPLIANCE"
}
}
Criar um website estático hospedado
Essa operação requer permissões, já que apenas o proprietário do depósito geralmente tem permissão para configurar um depósito para hospedar um website estático Os parâmetros determinam o sufixo padrão para os visitantes do site, bem como um documento de erro opcional incluído aqui para concluir o exemplo
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
}
Criação de uma política de backup
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)
}
Listagem de uma política de backup
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)
}
Tenha uma política de backup
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)
}
Excluir uma política de backup
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)
}
Criação de um cofre de backup
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)
}
Listagem de cofres de backup
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)
}
Obter cofres de backup
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)
}
Atualizar cofres de backup
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)
}
Excluir um cofre de backup
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)
}
}
Faixas de recuperação de listagem
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)
}
Obter faixa de recuperação
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)
}
Atualizar intervalos de recuperação
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)
}
Iniciando uma restauração
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)
}
Restauração de listagem
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)
}
Obter detalhes da restauração
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)
}
Criar um novo bucket Cloud Object Storage com bloqueio de objeto ativado
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 !!! ")
}
}
Colocar a configuração de bloqueio de objeto com modo de conformidade no bucket 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)
}
Colocar a configuração de bloqueio de objeto com modo de governança no bucket 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)
}
Obter a configuração de bloqueio de objeto no bucket 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)
}
}
Faça upload de um objeto com o modo de governança para o bucket 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!!! ")
}
}
Ative a retenção de bloqueio de objeto com o modo de conformidade no objeto
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)
}
Ative a retenção de bloqueio de objeto com o modo de governança no objeto
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)
}
Obter retenção de bloqueio de objeto
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)
}
}
Colocar objeto em bloqueio legal
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)
}
Obter bloqueio de objeto legalhold
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)
}
}
Exclusão de um objeto com modo de governança de bloqueio de objeto que usa governança de desvio
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")
}
}
Próximas etapas
Se você ainda não o fez, consulte a documentação detalhada da classe e do método disponível na documentação da API do Go.