Utilizzo di Go

Fine del supporto il 6 agosto 2027. Il supporto per l'SDK di COS ( IBM Cloud® Object Storage ) v1 terminerà il 6 agosto 2027. Dopo tale data, non riceverà più aggiornamenti, correzioni di sicurezza né nuove versioni. Consigliamo di passare all'SDK Go di IBM Cloud Object Storage v2, che offre prestazioni migliorate, maggiore sicurezza, API moderne e supporto continuo da parte di IBM.

IBM Cloud® Object Storage SDK for Go fornisce funzioni per utilizzare in modo ottimale IBM Cloud Object Storage.

IBM Cloud Object Storage SDK for Go è completo, con molte funzioni e funzionalità che vanno oltre l'ambito e lo spazio di questa guida. Per una documentazione dettagliata sulle classi e sui metodi, consultare la documentazione dell'API di Go. Il codice sorgente è disponibile nel repository GitHub.

Ottenimento dell'SDK

Utilizza go get per richiamare l'SDK per aggiungerlo al tuo spazio di lavoro GOPATH o alle dipendenze di modulo Go del progetto. L'SDK richiede una versione minima di Go 1.10 e una versione massima di Go 1.12. Le versioni future di Go dovrebbero essere supportate una volta completato il nostro processo di controllo qualità.

go get github.com/IBM/ibm-cos-sdk-go

Per aggiornare l'SDK, visita la pagina go get -u per scaricare l'ultima versione dell'SDK.

go get -u github.com/IBM/ibm-cos-sdk-go

Importa pacchetti

Dopo che hai installato l'SDK, dovrai importare i pacchetti di cui hai bisogno nelle tue applicazioni Go per utilizzare l'SDK, come mostrato nel seguente esempio:

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"
)

Creazione di un cliente e acquisizione delle credenziali del servizio

Per stabilire una connessione a IBM Cloud Object Storage, un client viene creato e configurato fornendo le informazioni delle credenziali (chiave API e ID istanza del servizio). Questi valori possono anche essere derivati automaticamente da un file di credenziali o dalle variabili di ambiente.

Le credenziali possono essere trovate creando una credenziale del servizio o tramite la CLI.

La Figura 1 mostra un esempio di come definire le variabili di ambiente in un runtime dell'applicazione nel portale IBM Cloud Object Storage. Le variabili richieste sono: IBM_API_KEY_ID , che contiene le credenziali del servizio apikey; ` `IBM_SERVICE_INSTANCE_ID` `, che contiene l' `resource_instance_id` , anch'esso ricavato dalle credenziali del servizio; e ` `IBM_AUTH_ENDPOINT` `, con un valore adeguato al proprio account, ad esempio ` `https://iam.cloud.ibm.com/identity/token. Se stai utilizzando le variabili di ambiente per definire le tue credenziali dell'applicazione, utilizza WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig()))., sostituendo il metodo simile utilizzato nell'esempio di configurazione.

variabili d'ambiente
variabili d'ambiente

Se si esegue la migrazione da AWS S3, puoi anche derivare i dati delle credenziali da ~/.aws/credentials nel formato:

[default]
aws_access_key_id = {ACCESS_KEY}
aws_secret_access_key = {SECRET_ACCESS_KEY}

Se esistono ~/.bluemix/cos_credentials e ~/.aws/credentials, cos_credentials ha la precedenza.

Inizializzazione della configurazione

// 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)

Creare un client e reperire le credenziali del profilo attendibile per le risorse computerizzate

Un client può essere creato fornendo le credenziali del servizio o le credenziali del profilo di fiducia. Questa sezione fornisce informazioni per creare un client utilizzando le credenziali del profilo attendibile.

Per connettersi a IBM Cloud Object Storage, viene creato un client che può essere configurato anche fornendo le informazioni sulle credenziali del profilo di fiducia (ID del profilo di fiducia e percorso del file del token CR). Questi valori possono anche essere originati automaticamente da variabili di ambiente.

Per creare un profilo attendibile, stabilire l'attendibilità con le risorse di calcolo in base a specifici attributi e definire una politica per assegnare l'accesso alle risorse, consulta Gestione dell'accesso per le app nelle risorse di calcolo.

Per ulteriori informazioni su come stabilire l'affidabilità con un cluster Kubernetes, vedi Utilizzo dei profili attendibili nei tuoi cluster Kubernetes e OpenShift

GO SDK supporta l'autenticazione tramite profilo trusted solo nei cluster Kubernetes e OpenShift.

Le credenziali del profilo attendibile possono essere impostate come variabili d'ambiente durante l'esecuzione dell'applicazione. Le variabili richieste sono TRUSTED_PROFILE_ID che contiene l'ID del profilo di fiducia trusted profile id, CR_TOKEN_FILE_PATH che contiene il codice service account token file path, IBM_SERVICE_INSTANCE_ID che contiene il codice resource_instance_id della credenziale di servizio e IBM_AUTH_ENDPOINT con un valore appropriato al proprio account, come https://iam.cloud.ibm.com/identity/token. Se stai utilizzando le variabili di ambiente per definire le tue credenziali dell'applicazione, utilizza WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig()))., sostituendo il metodo simile utilizzato nell'esempio di configurazione.

Inizializzazione della configurazione

// 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)

Sia API-Key che Trusted-Profile-ID non possono essere impostati come variabili ambientali. Solo uno di essi deve essere impostato, altrimenti il GO SDK lancia un errore.

Per ulteriori informazioni sugli endpoint, vedi Endpoint e ubicazioni di archiviazione.

Creazione di un client e reperimento delle credenziali del profilo attendibile per Service ID

È ora possibile creare un client che si autentica a IBM Cloud Object Storage utilizzando un Service ID e un Trusted Profile. I profili affidabili consentono alle identità di IBM Cloud di accedere alle risorse di un account senza richiedere l'appartenenza diretta a tale account. Associando un Service ID a un Profilo di fiducia, è possibile garantirgli l'accesso sicuro alle risorse, comprese quelle situate in diversi account IBM Cloud. Per maggiori dettagli, consultare la documentazione di IBM Cloud sulla creazione di profili di fiducia per gli ID servizio.

Prima di iniziare

  1. Creare un ID servizio nell'account di origine.
    • Nell'ID servizio, creare una chiave API e annotare il valore della chiave API.
  2. Creare un profilo di fiducia nell'account di destinazione e associare l'ID servizio dell'account di origine. Vedere Stabilire la fiducia con gli ID dei servizi nella console. L'account di destinazione è l'account che contiene le risorse a cui accedere.
  3. Assegnare l'accesso appropriato al profilo di fiducia.

Autenticazione tramite l'ID del servizio e il profilo di fiducia

Una volta completata l'impostazione, utilizzare l'SDK Go per creare un client che si autentichi utilizzando il Service ID e il Trusted Profile.

  1. Impostazione della configurazione del client utilizzando l'ID profilo attendibile:

    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)
    }
    
  2. Impostare la configurazione del client utilizzando il nome del profilo di fiducia:

    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)
    }
    

Quando si utilizza il nome del profilo di fiducia, è necessario fornire anche l'ID dell'account che possiede il profilo di fiducia.

Le credenziali del profilo attendibile possono essere fornite anche tramite variabili d'ambiente in fase di esecuzione.

  1. Configurazione del client mediante variabili d'ambiente con ID profilo attendibile:

    1. Impostare queste variabili d'ambiente nell'ambiente di runtime.

      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"
      
    2. Configurare il client.

      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)
      
  2. Configurare il client utilizzando le variabili d'ambiente con il nome del profilo di fiducia:

    1. Impostare queste variabili d'ambiente nell'ambiente di runtime.

      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"
      
    2. Configurare il client.

      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)
      

Sostituire i valori segnaposto con CRN, chiavi API, nomi o ID di profili, endpoint e ID di account reali.

Esempi di codici

Creazione di un nuovo bucket

È possibile che si faccia riferimento a un elenco di codici di provisioning validi per LocationConstraint nella guida alle classi di archiviazione.

L'esempio utilizza il vincolo di ubicazione appropriato per lo storage Cold Vault in base alla configurazione dell'esempio. La posizione e la configurazione potrebbero variare.

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)
}

Elenca i bucket disponibili

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Call Function
    d, _ := client.ListBuckets(&s3.ListBucketsInput{})
    fmt.Println(d)
}

Caricare un oggetto in un bucket

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)
}

Elencare gli elementi contenuti in un bucket (Elenco degli oggetti 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: ""
//}

Ottieni il contenuto di un oggetto

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)
}

Eliminare un oggetto da un bucket

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)
}

Eliminare più oggetti da un bucket

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)
}

Elimina un bucket

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)
}

Esegui un caricamento in più parti manuale

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)
}

Utilizzo di Key Protect

Key Protect può essere aggiunto a un bucket di archiviazione per gestire le chiavi di crittografia. Tutti i dati vengono crittografati in IBM Cloud Object Storage, ma Key Protect offre un servizio che consente di generare, ruotare e controllare l'accesso alle chiavi di crittografia tramite un servizio centralizzato.

Prima di cominciare

Per creare un bucket con Key-Protect abilitato sono necessari i seguenti elementi:

Richiamo del CRN di chiave root

  1. Richiama l'ID istanza per il tuo servizio Key Protect
  2. Utilizza l'API Key Protect per richiamare tutte le tue chiavi disponibili
  3. Recupera il CRN della chiave principale che utilizzi per abilitare la funzione " Key Protect " sul tuo bucket. Il CRN ha un aspetto simile al seguente:

crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234

Creazione di un bucket con Key Protect abilitato

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)
}

Valori chiave

  • <NEW_BUCKET_NAME>- Il nome del nuovo bucket.
  • <ROOT-KEY-CRN>- CRN della chiave principale ottenuta dal servizio Key Protect.
  • <ALGORITHM>- L'algoritmo di crittografia utilizzato per i nuovi oggetti aggiunti al bucket (l'impostazione predefinita è " AES256 ").

Utilizza il gestore trasferimenti

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)
}

Ottenimento di un elenco esteso

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))
}

Valori chiave

  • <MAX_KEYS>- Numero massimo di bucket da recuperare nella richiesta.
  • <MARKER>- Il nome del bucket da cui iniziare l'elenco (salta fino a questo bucket).
  • <PREFIX- Includere solo i bucket il cui nome inizia con questo prefisso.

Ottenimento di un elenco esteso con la paginazione

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)
	}
}

Valori chiave

  • <MAX_KEYS>- Numero massimo di bucket da recuperare nella richiesta.
  • <MARKER>- Il nome del bucket da cui iniziare l'elenco (salta fino a questo bucket).
  • <PREFIX- Includere solo i bucket il cui nome inizia con questo prefisso.

Supporto livello archivio

È possibile archiviare automaticamente gli oggetti dopo un periodo di tempo specificato o dopo una data specificata. Una volta archiviata, una copia temporanea di un oggetto può essere ripristinata per l'accesso come necessario.

Il tempo necessario per ripristinare la copia temporanea di uno o più oggetti può richiedere fino a 12 ore.

Per utilizzare l'esempio fornito, fornire la propria configurazione, compresa la sostituzione di <apikey> e altre informazioni tra parentesi di <...>, tenendo presente che l'uso di variabili d'ambiente è più sicuro e che non si dovrebbero inserire le credenziali nel codice che sarà sottoposto a modifiche di versione.

Una politica di archivio viene impostata a livello bucket richiamando il metodo PutBucketLifecycleConfiguration su una istanza del client. Una politica di archiviazione appena aggiunta o modificata si applica ai nuovi oggetti caricati e non influisce su quelli esistenti.

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 risposta tipica è esemplificata qui.

 {
   Rules: [{
       Filter: {
       },
       ID: "id3",
       Status: "Enabled",
       Transitions: [{
           Days: 5,
           StorageClass: "GLACIER"
         }]
     }]
 }

Immutable Object Storage

Gli utenti possono configurare i bucket con un criterio Immutable Object Storage per impedire che gli oggetti vengano modificati o eliminati per un periodo definito. Il periodo di conservazione può essere specificato per oggetto oppure gli oggetti possono ereditare un periodo di conservazione predefinito impostato sul bucket. È anche possibile impostare periodi di conservazione illimitati e permanenti. Immutable Object Storage soddisfa le regole stabilite dalla SEC che governa la conservazione dei record e gli amministratori di IBM Cloud non sono in grado di ignorare queste restrizioni.

Immutable Object Storage non supporta i trasferimenti Aspera attraverso l'SDK per caricare oggetti o directory in questa 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 risposta tipica è esemplificata qui.

 {
   ProtectionConfiguration: {
     DefaultRetention: {
       Days: 100
     },
     MaximumRetention: {
       Days: 1000
     },
     MinimumRetention: {
       Days: 10
     },
     Status: "COMPLIANCE"
   }
 }

Crea un sito web statico ospitato

Questa operazione richiede le autorizzazioni, poiché solo al proprietario del bucket è generalmente consentito configurare un bucket per ospitare un sito web statico. I parametri determinano il suffisso predefinito per i visitatori del sito e un documento di errore facoltativo incluso qui per completare l'esempio.

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(&params)
	fmt.Println(p)
	fmt.Println(e) // see response for results
}

Creazione di un criterio di 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)
}

Elencare un criterio di 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)
}

Ottenere una politica di 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)
}

Eliminare un criterio di 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)
}

Creazione di un vault di 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)
}

Elenco delle camere blindate di 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)
}

Ottenere i vault di 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)
}

Aggiornare i vault di 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)
}

Eliminare un vault di 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)
    }
}

Elenco Gamme di recupero

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)
}

Ottenere l'intervallo di recupero

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)
}

Aggiornare gli intervalli di recupero

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)
}

Avvio di un ripristino

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)
}

Ripristino dell'elenco

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)
}

Ottenere i dettagli del ripristino

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)
}

Creare un nuovo bucket Cloud Object Storage con il blocco degli oggetti abilitato

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 !!! ")
    }
}

Mettere la configurazione del blocco degli oggetti con la modalità di conformità sul 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)
}

Mettere la configurazione del blocco degli oggetti con la modalità di governance sul secchio 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)
}

Ottenere la configurazione del blocco degli oggetti sul secchio 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)
    }
}

Caricare un oggetto con modalità di governance nel 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!!! ")
    }
}

Attiva la conservazione del blocco dell'oggetto con modalità di conformità sull'oggetto

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)
}

Attiva la conservazione del blocco dell'oggetto con modalità di governance sull'oggetto

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)
}

Ottieni il mantenimento del blocco dell'oggetto

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)
    }
}

Applicare il blocco legale all'oggetto

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)
}

Ottieni il blocco dell'oggetto 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)
    }
}

Eliminazione di un oggetto con modalità di governance del blocco degli oggetti che utilizza la governance di 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")
    }
}

Passi successivi

Se non l'avete ancora fatto, consultate la documentazione dettagliata delle classi e dei metodi disponibile nella documentazione dell'API di Go.