Utilización de Go
Fin del soporte técnico el 6 de agosto de 2027. El SDK de COS ( IBM Cloud® Object Storage ) v1 dejará de recibir soporte el 6 de agosto de 2027. A partir de esa fecha, dejará de recibir actualizaciones, correcciones de seguridad o nuevas versiones. Recomendamos migrar al SDK de Go de « IBM Cloud Object Storage » v2, que ofrece un mejor rendimiento, mayor seguridad, API modernas y soporte técnico continuo en IBM.
El SDK de IBM Cloud® Object Storage para Go proporciona características para aprovechar al máximo IBM Cloud Object Storage.
El SDK de IBM Cloud Object Storage para Go es muy completo y ofrece varias características y prestaciones que van más allá del ámbito y del espacio de esta guía. Para obtener información detallada sobre las clases y los métodos, consulta la documentación de la API de Go. El código fuente se puede encontrar en el repositorio GitHub.
Obtención del SDK
Utilice go get para recuperar el SDK para añadirlo al espacio de trabajo GOPATH o a las dependencias de módulo Go del proyecto. El SDK requiere una versión mínima de Go 1.10 y una versión máxima de Go 1.12. Las futuras versiones
de Go deberían ser compatibles una vez que se haya completado nuestro proceso de control de calidad.
go get github.com/IBM/ibm-cos-sdk-go
Para actualizar el SDK, utiliza go get -u para descargar la última versión del SDK.
go get -u github.com/IBM/ibm-cos-sdk-go
Importación de paquetes
Después de instalar el SDK, tendrá que importar los paquetes que necesite en las aplicaciones Go para utilizar el SDK, tal como se muestra en el ejemplo siguiente:
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"
)
Creación de un cliente y obtención de las credenciales del servicio
Para conectarse a IBM Cloud Object Storage, se crea y se configura un cliente proporcionando información de credenciales (clave de API e ID de instancia de servicio). Estos valores también se pueden tomar automáticamente de un archivo de credenciales o de variables de entorno.
Puede encontrar las credenciales creando una credencial de servicio o a través de la CLI.
En la Figura 1 se muestra un ejemplo de cómo definir las variables de entorno en un tiempo de ejecución de aplicaciones en el portal de IBM Cloud Object Storage. Las variables necesarias son « IBM_API_KEY_ID », que contiene tu credencial
de servicio « apikey », « IBM_SERVICE_INSTANCE_ID », que contiene el « resource_instance_id » (también de tu credencial de servicio), y « IBM_AUTH_ENDPOINT », con un valor adecuado para tu
cuenta, como « https://iam.cloud.ibm.com/identity/token ». Si utiliza variables de entorno para definir las credenciales de la aplicación, utilice WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). para sustituir
el método similar utilizado en el ejemplo de configuración.
Si se migra desde AWS S3, también puede obtener los datos de credenciales de origen de ~/.aws/credentials en el formato:
[default]
aws_access_key_id = {ACCESS_KEY}
aws_secret_access_key = {SECRET_ACCESS_KEY}
Si existen tanto ~/.bluemix/cos_credentials como ~/.aws/credentials, prevalece cos_credentials.
Inicialización de la configuración
// 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)
Creación de un cliente y obtención de credenciales de perfil de confianza para recursos computarizados
Se puede crear un cliente proporcionando credenciales de servicio o credenciales de perfil de confianza. Esta sección proporciona información para crear un cliente utilizando credenciales de perfil de confianza.
Para conectarse a IBM Cloud Object Storage, se crea un cliente que también puede configurarse proporcionando información de credenciales de perfil de confianza (ID de perfil de confianza y ruta del archivo CR Token). Estos valores también se pueden obtener automáticamente de las variables de entorno.
Para crear un perfil de confianza, estableciendo la confianza con recursos de cálculo basados en atributos específicos, y para definir una política para asignar acceso a recursos, consulte Gestión del acceso para apps en recursos de cálculo.
Para obtener más información sobre cómo establecer una relación de confianza con un clúster de « Kubernetes », consulta «Uso de perfiles de confianza en tus clústeres de Kubernetes y OpenShift ».
GO SDK admite la autenticación mediante el uso de perfiles de confianza sólo en los clústeres Kubernetes y OpenShift.
Las credenciales del perfil de confianza pueden establecerse como variables de entorno durante el tiempo de ejecución de la aplicación. Las variables requeridas son TRUSTED_PROFILE_ID que contiene el ID de su perfil de confianza
trusted profile id, CR_TOKEN_FILE_PATH que contiene el service account token file path, IBM_SERVICE_INSTANCE_ID que contiene el resource_instance_id de su credencial de servicio,
y un IBM_AUTH_ENDPOINT con un valor apropiado para su cuenta, como https://iam.cloud.ibm.com/identity/token. Si utiliza variables de entorno para definir las credenciales de la aplicación, utilice WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). para sustituir el método similar utilizado en el ejemplo de configuración.
Inicialización de la configuración
// 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 API-Key como Trusted-Profile-ID no pueden establecerse como variables de entorno. Sólo uno de ellos debe ser establecido, de lo contrario el GO SDK arrojará un error.
Para obtener más información sobre puntos finales, consulte Puntos finales y ubicaciones de almacenamiento.
Creación de un cliente y obtención de credenciales de perfil de confianza para Service ID
Ahora puede crear un cliente que se autentique en IBM Cloud Object Storage utilizando un ID de servicio junto con un perfil de confianza. Los perfiles de confianza permiten a las identidades de IBM Cloud acceder a los recursos de una cuenta sin necesidad de pertenecer directamente a ella. Al asociar un ID de servicio a un perfil de confianza, puede concederle acceso seguro a los recursos, incluidos los ubicados en diferentes cuentas de IBM Cloud. Para más detalles, consulte la documentación de IBM Cloud sobre la creación de perfiles de confianza para ID de servicio.
Antes de empezar
- Cree un ID de servicio en la cuenta de origen.
- En el ID de servicio, cree una clave API y anote el valor de la clave API.
- Cree un perfil de confianza en la cuenta de destino y asocie el ID de servicio de la cuenta de origen. Véase Establecer la confianza con los ID de servicio en la consola. La cuenta de destino es la cuenta que contiene los recursos a los que se va a acceder.
- Asigne el acceso adecuado al perfil de confianza.
Autenticación mediante el ID de servicio y el perfil de confianza
Una vez finalizada la configuración, utilice el SDK Go para crear un cliente que se autentique utilizando el ID de servicio y el perfil de confianza.
-
Establecimiento de la configuración del cliente mediante el ID de perfil de confianza:
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) } -
Establecimiento de la configuración del cliente mediante el nombre del perfil de confianza:
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) }
Cuando utilice el nombre del perfil de confianza, también debe proporcionar el ID de la cuenta a la que pertenece el perfil de confianza.
Las credenciales del perfil de confianza también pueden proporcionarse a través de variables de entorno en tiempo de ejecución.
-
Configuración del cliente mediante variables de entorno con ID de perfil de confianza:
-
Establezca estas variables de entorno en su entorno de ejecución.
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 el 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)
-
-
Configuración del cliente mediante variables de entorno con nombre de perfil de confianza:
-
Establezca estas variables de entorno en su entorno de ejecución.
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 el 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)
-
Sustituya los valores de los marcadores de posición por CRN, claves API, nombres o ID de perfil, puntos finales e ID de cuenta reales.
Ejemplos de código
Creación de un nuevo grupo
Puede consultar la lista de códigos de suministro válidos para LocationConstraint en la guía de Storage Classes.
La muestra utiliza la restricción de ubicación adecuada para el almacenamiento Cold Vault en función de la configuración de la muestra. Su ubicación y configuración pueden 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)
}
Obtención de una lista de grupos disponibles
func main() {
// Create client
sess := session.Must(session.NewSession())
client := s3.New(sess, conf)
// Call Function
d, _ := client.ListBuckets(&s3.ListBucketsInput{})
fmt.Println(d)
}
Carga de un objeto en un grupo
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)
}
Enumerar elementos de un 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: ""
//}
Obtención del contenido de un 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)
}
Supresión de un objeto de un grupo
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)
}
Suprimir varios objetos de un grupo
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)
}
Supresión de un grupo
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)
}
Ejecución manual de una carga de varias 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)
}
Utilización de Key Protect
Key Protect se puede añadir a un grupo de almacenamiento para gestionar claves de cifrado. Todos los datos se cifran mediante el protocolo IBM Cloud Object Storage, pero Key Protect ofrece un servicio para generar, rotar y controlar el acceso a las claves de cifrado mediante un servicio centralizado.
Antes de empezar
Para crear un bucket con la función Key-Protect activada, se necesitan los siguientes elementos:
- Un servicio de Key Protect suministrado
- Se dispone de una clave raíz ( generada o importada )
Recuperación del CRN de la clave raíz
- Recupere el ID de instancia del servicio Key Protect
- Utilice la API de Key Protect para recuperar todas las claves disponibles
- Puede utilizar mandatos
curlo un cliente de API REST, como Postman, para acceder a la API de Key Protect.
- Puede utilizar mandatos
- Obtén el CRN de la clave raíz que utilizas para habilitar la función « Key Protect » en tu depósito. El CRN tiene un aspecto similar al siguiente:
crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234
Creación de un grupo con Key Protect habilitado
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 de clave
<NEW_BUCKET_NAME>- El nombre del nuevo depósito.<ROOT-KEY-CRN>- El CRN de la clave raíz obtenido del servicio Key Protect.<ALGORITHM>- El algoritmo de cifrado que se utiliza para los nuevos objetos añadidos al depósito (el valor por defecto es « AES256 »).
Utilización del gestor de transferencias
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)
}
Obtención de una lista 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 de clave
<MAX_KEYS>- Número máximo de buckets que se pueden recuperar en la solicitud.<MARKER>- El nombre del bucket a partir del cual se iniciará la lista (omitir hasta este bucket).<PREFIX- Incluye únicamente los buckets cuyo nombre comience por este prefijo.
Obtención de una lista ampliada con paginación
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 de clave
<MAX_KEYS>- Número máximo de buckets que se pueden recuperar en la solicitud.<MARKER>- El nombre del bucket a partir del cual se iniciará la lista (omitir hasta este bucket).<PREFIX- Incluye únicamente los buckets cuyo nombre comience por este prefijo.
Soporte de nivel de archivado
Puede archivar automáticamente objetos después de un periodo de tiempo especificado o después de una fecha especificada. Una vez archivada, se puede restaurar una copia temporal de un objeto para el acceso según sea necesario.
El tiempo necesario para restaurar la copia temporal de uno o varios objetos puede llegar a ser de 12 horas.
Para utilizar el ejemplo proporcionado, proporcione su propia configuración incluyendo la sustitución de <apikey> y otra información entre corchetes <...>, teniendo en cuenta que el uso de variables de
entorno es más seguro, y no debe poner credenciales en código que será versionado.
Una política de archivado se establece a nivel de grupo llamando al método PutBucketLifecycleConfiguration en una instancia de cliente. Una política de archivado recién añadida o modificada se aplica a los nuevos objetos cargados
y no afecta a los 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)
}
La respuesta típica se ejemplifica aquí.
{
Rules: [{
Filter: {
},
ID: "id3",
Status: "Enabled",
Transitions: [{
Days: 5,
StorageClass: "GLACIER"
}]
}]
}
Immutable Object Storage
Los usuarios pueden configurar buckets con una política inmutable Object Storage para evitar que los objetos se modifiquen o eliminen durante un periodo definido. El periodo de retención se puede especificar por objeto, o los objetos pueden heredar un periodo de retención predeterminado establecido en el grupo. También es posible establecer periodos de retención abiertos y permanentes. El Object Storage inmutable cumple las reglas establecidas por SEC que rigen la retención de registros, y los administradores de IBM Cloud no pueden eludir estas restricciones.
Immutable Object Storage no admite transferencias Aspera a través del SDK para cargar objetos o directorios en esta fase.
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)
}
La respuesta típica se ejemplifica aquí.
{
ProtectionConfiguration: {
DefaultRetention: {
Days: 100
},
MaximumRetention: {
Days: 1000
},
MinimumRetention: {
Days: 10
},
Status: "COMPLIANCE"
}
}
Crear un sitio web estático alojado
Esta operación requiere permisos, ya que normalmente solo se permite al propietario del grupo configurar un grupo para alojar un sitio web estático. Los parámetros determinan el sufijo predeterminado para los visitantes del sitio, así como un documento de error opcional que se incluye aquí para completar el ejemplo.
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
}
Creación de una política de copias de seguridad
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)
}
Listado de una política de copias de seguridad
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)
}
Obtener una política de copias de seguridad
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)
}
Eliminar una política de copia de seguridad
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)
}
Creación de una copia de seguridad
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)
}
Listado de bóvedas de seguridad
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)
}
Obtener bóvedas de seguridad
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)
}
Actualizar bóvedas de seguridad
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)
}
Eliminar una copia de seguridad
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)
}
}
Rangos de recuperación de listados
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)
}
Obtenga Rango de Recuperación
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)
}
Actualizar los intervalos de recuperación
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)
}
Iniciar una restauración
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)
}
Restaurar listado
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)
}
Obtener detalles de restauración
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)
}
Crear un nuevo cubo Cloud Object Storage con el bloqueo de objetos activado
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 !!! ")
}
}
Ponga la configuración de bloqueo de objetos con el modo de cumplimiento en Cloud Object Storage bucket
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)
}
Ponga la configuración de bloqueo de objetos con el modo de gobierno en Cloud Object Storage bucket
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)
}
Obtener la configuración de bloqueo de objetos en Cloud Object Storage bucket
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)
}
}
Cargar un objeto con modo de gobernanza en el 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!!! ")
}
}
Activar la retención del bloqueo de objetos con el modo de cumplimiento en el 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)
}
Activar la retención de bloqueo de objetos con el modo de gobernanza en el 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)
}
Obtener retención de bloqueo de objetos
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)
}
}
Poner objeto bajo bloqueo 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)
}
Obtener bloqueo 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)
}
}
Eliminación de un objeto con modo de gobernanza de bloqueo de objeto que utiliza gobernanza de bypass
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óximos pasos
Si aún no lo ha hecho, consulte la documentación detallada de clases y métodos disponible en la documentación de la API Go.