Go verwenden

Ende des Supports am 6. August 2027. Der Support für das COS-SDK ( IBM Cloud® Object Storage ) v1 endet am 6. August 2027. Nach diesem Datum werden keine Updates, Sicherheitspatches oder neuen Versionen mehr bereitgestellt. Wir empfehlen die Umstellung auf das „ IBM Cloud Object Storage “-SDK für Go(v2), das eine verbesserte Leistung, erhöhte Sicherheit, moderne APIs und fortlaufenden Support unter IBM bietet.

Das IBM Cloud® Object Storage-SDK für Go stellt Funktionen bereit, mit denen IBM Cloud Object Storage optimal genutzt werden kann.

Das IBM Cloud Object Storage-SDK für Go ist umfassend und verfügt über zahlreiche Komponenten und Funktionen, deren Behandlung den Rahmen des vorliegenden Handbuchs übersteigen würde. Ausführliche Informationen zu Klassen und Methoden finden Sie in der Go-API-Dokumentation. Der Quellcode ist im Repository „ GitHub “ zu finden.

SDK abrufen

Verwenden Sie go get zum Abrufen des SDKs, um es zum Arbeitsbereich GOPATH oder den GO-Modulabhängigkeiten des Projekts hinzuzufügen. Das SDK erfordert mindestens die Version Go 1.10 und höchstens die Version Go 1.12. Zukünftige Versionen von Go sollten unterstützt werden, sobald unser Qualitätskontrollprozess abgeschlossen ist.

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

Um das SDK zu aktualisieren, rufen Sie go get -u auf, um die neueste Version des SDK abzurufen.

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

Pakete importieren

Nachdem Sie das SDK installiert haben, müssen Sie die benötigten Pakete wie im folgenden Beispiel dargestellt in Ihre Go-Anwendungen importieren, damit das SDK verwendet werden kann:

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

Anlegen eines Mandanten und Abrufen der Service-Anmeldedaten

Zum Herstellen einer Verbindung zu IBM Cloud Object Storage wird ein Client erstellt und durch Bereitstellen der Berechtigungsnachweisinformationen (API-Schlüssel und Serviceinstanz-ID) konfiguriert. Diese Werte können auch automatisch aus einer Berechtigungsnachweisdatei oder aus Umgebungsvariablen abgeleitet werden.

Die Berechtigungsnachweise können durch Erstellen eines Serviceberechtigungsnachweises oder über eine Befehlszeilenschnittstelle gesucht werden.

In Abbildung 1 wird ein Beispiel für die Verwendungshinweise zum Definieren von Umgebungsvariablen in einer Anwendungslaufzeit im IBM Cloud Object Storage-Portal dargestellt. Die erforderlichen Variablen sind „ IBM_API_KEY_ID “, das Ihre Service-Anmeldeinformationen enthält („ apikey “), „ IBM_SERVICE_INSTANCE_ID “, das die „ resource_instance_id “ enthält (ebenfalls aus Ihren Service-Anmeldeinformationen), sowie „ IBM_AUTH_ENDPOINT “ mit einem für Ihr Konto geeigneten Wert, wie beispielsweise „ https://iam.cloud.ibm.com/identity/token “. Falls Sie zum Definieren der Anwendungsberechtigungsnachweise Umgebungsvariablen verwenden möchten, sollten Sie WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). benutzen; dadurch wird die ähnliche Methode ersetzt, die im Konfigurationsbeispiel verwendet wird.

Umgebungsvariablen
Umgebungsvariablen

Falls Sie eine Migration von AWS S3 durchführen, können Sie die Daten für die Berechtigungsnachweise aus ~/.aws/credentials im folgenden Format verwenden:

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

Wenn sowohl ~/.bluemix/cos_credentials als auch ~/.aws/credentials vorhanden ist, genießt cos_credentials Vorrang.

Konfiguration initialisieren

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

Erstellen eines Mandanten und Beschaffung von vertrauenswürdigen Profilanmeldeinformationen für berechnete Ressourcen

Ein Client kann durch Angabe von Dienstanmeldedaten oder vertrauenswürdigen Profilanmeldedaten erstellt werden. Dieser Abschnitt enthält Informationen zur einen Client unter Verwendung vertrauenswürdiger Profilanmeldeinformationen zu erstellen.

Um eine Verbindung zu IBM Cloud Object Storage herzustellen, wird ein Client erstellt, der auch konfiguriert werden kann, indem vertrauenswürdige Profilinformationen (vertrauenswürdige Profil-ID und CR-Token-Dateipfad) angegeben werden. Diese Werte können auch automatisch aus Umgebungsvariablen abgeleitet werden.

Informationen zum Erstellen eines vertrauenswürdigen Profils, zum Herstellen einer Vertrauensbeziehung mit Rechenressourcen basierend auf bestimmten Attributen und zum Definieren einer Richtlinie für die Zuweisung von Zugriff auf Ressourcen finden Sie unter Zugriff für Apps in Rechenressourcen verwalten.

Weitere Informationen zum Einrichten von Vertrauensbeziehungen in einem „ Kubernetes “-Cluster finden Sie unter „ Verwendung vertrauenswürdiger Profile in Ihren „ Kubernetes “- und „ OpenShift “-Clustern

GO SDK unterstützt die Authentifizierung mit einem vertrauenswürdigen Profil nur in Kubernetes und OpenShift Clustern.

Vertrauenswürdige Profildaten können während der Anwendungslaufzeit als Umgebungsvariablen festgelegt werden. Die erforderlichen Variablen sind TRUSTED_PROFILE_ID mit Ihrer vertrauenswürdigen Profil-ID trusted profile id, CR_TOKEN_FILE_PATH mit der service account token file path, IBM_SERVICE_INSTANCE_ID mit der resource_instance_id Ihres Dienstausweises und eine IBM_AUTH_ENDPOINT mit einem für Ihr Konto geeigneten Wert, wie https://iam.cloud.ibm.com/identity/token. Falls Sie zum Definieren der Anwendungsberechtigungsnachweise Umgebungsvariablen verwenden möchten, sollten Sie WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())). benutzen; dadurch wird die ähnliche Methode ersetzt, die im Konfigurationsbeispiel verwendet wird.

Konfiguration initialisieren

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

Sowohl API-Key als auch Trusted-Profile-ID können nicht als Umgebungsvariablen gesetzt werden. Es sollte nur eines davon gesetzt werden, da sonst das GO SDK einen Fehler auslösen.

Weitere Informationen zu Endpunkten enthält Endpunkte und Speicherpositionen.

Erstellen eines Mandanten und Beschaffung von vertrauenswürdigen Profilanmeldeinformationen für Service ID

Sie können nun einen Client erstellen, der sich bei IBM Cloud Object Storage mit einer Service-ID und einem vertrauenswürdigen Profil authentifiziert. Vertrauenswürdige Profile ermöglichen IBM Cloud Identitäten den Zugriff auf Ressourcen in einem Konto, ohne dass eine direkte Mitgliedschaft in diesem Konto erforderlich ist. Indem Sie eine Service-ID mit einem vertrauenswürdigen Profil verknüpfen, können Sie ihr auf sichere Weise Zugriff auf Ressourcen gewähren, auch auf solche, die sich in verschiedenen IBM Cloud Konten befinden. Weitere Einzelheiten finden Sie in der Dokumentation IBM Cloud zum Erstellen von vertrauenswürdigen Profilen für Service-IDs.

Vorbereitende Schritte

  1. Erstellen Sie eine Service-ID im Quellkonto.
    • Erstellen Sie in der Dienst-ID einen API-Schlüssel und notieren Sie den API-Schlüsselwert.
  2. Erstellen Sie ein vertrauenswürdiges Profil im Zielkonto und verknüpfen Sie die Service-ID des Quellkontos. Siehe Vertrauensbildung mit Dienst-IDs in der Konsole. Das Zielkonto ist das Konto, das die Ressourcen enthält, auf die zugegriffen werden soll.
  3. Weisen Sie dem vertrauenswürdigen Profil den entsprechenden Zugriff zu.

Authentifizierung mit Hilfe der Service-ID und des vertrauenswürdigen Profils

Sobald die Einrichtung abgeschlossen ist, verwenden Sie das Go SDK, um einen Client zu erstellen, der sich mit Hilfe der Service-ID und des vertrauenswürdigen Profils authentifiziert.

  1. Einrichten der Client-Konfiguration mit Hilfe der vertrauenswürdigen Profil-ID:

    package main
    import (
        "fmt"
        "os"
        "github.com/IBM/ibm-cos-sdk-go/aws"
        "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
        "github.com/IBM/ibm-cos-sdk-go/aws/session"
        "github.com/IBM/ibm-cos-sdk-go/service/s3"
    )
    const (
        serviceInstanceID  = "crn-of-target-cos-instance" // eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
        authEndpoint       = "https://iam.cloud.ibm.com/identity/token"
        serviceEndpoint   = "cos-endpoint"     //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud"
        trustedProfileId   = ""    // eg: "Profile-gxxxxx530-xxxx-xxxx-xxxx-abpxxxxb94"
        serviceIDApiKey = "api-key-of-service-id"
    )
    func TestTrustedProfile
    func main() {
        sess := session.Must(session.NewSession())
        conf := aws.NewConfig().
            WithRegion("us-south").
    WithEndpoint(serviceEndpoint).       WithCredentials(ibmiam.NewTrustedProfileCredentialsServiceIDWithTrustedProfileId(aws.NewConfig(), authEndpoint, trustedProfileId, serviceIDApiKey, serviceInstanceID)).
            WithS3ForcePathStyle(true)
        client := s3.New(sess, conf)
    }
    
  2. Einrichten der Client-Konfiguration mit Hilfe des vertrauenswürdigen Profilnamens:

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

Wenn Sie den Namen des vertrauenswürdigen Profils verwenden, müssen Sie auch die Konto-ID angeben, der das vertrauenswürdige Profil gehört.

Vertrauenswürdige Profilanmeldeinformationen können auch über Umgebungsvariablen zur Laufzeit bereitgestellt werden.

  1. Konfiguration des Clients durch Verwendung von Umgebungsvariablen mit vertrauenswürdiger Profil-ID:

    1. Setzen Sie diese Umgebungsvariablen in Ihrer Laufzeitumgebung.

      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. Konfigurieren Sie den 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. Konfiguration des Clients durch Verwendung von Umgebungsvariablen mit vertrauenswürdigem Profilnamen:

    1. Setzen Sie diese Umgebungsvariablen in Ihrer Laufzeitumgebung.

      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. Konfigurieren Sie den 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)
      

Ersetzen Sie Platzhalterwerte durch tatsächliche CRNs, API-Schlüssel, Profilnamen oder IDs, Endpunkte und Konto-IDs.

Codebeispiele

Neues Bucket erstellen

Auf eine Liste gültiger Bereitstellungscodes für LocationConstraint kann im Handbuch für Speicherklassen verwiesen werden.

Das Beispiel verwendet die entsprechende Standortbeschränkung für den Cold Vault-Speicher auf der Grundlage der Beispielkonfiguration. Ihre Standorte und Konfigurationen können abweichen.

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

Verfügbare Buckets auflisten

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

Objekt in Bucket hochladen

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

Elemente in einem Bucket auflisten (List Objects 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: ""
//}

Objektinhalt abrufen

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

Objekt in Bucket löschen

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

Mehrere Objekte in Bucket löschen

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

Bucket löschen

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

Mehrteiligen Upload manuell ausführen

func main() {
    // Variables
    bucket := "<BUCKET_NAME>"
    key := "<OBJECT_KEY>"
    content := bytes.NewReader([]byte("<CONTENT>"))
    input := s3.CreateMultipartUploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    }
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    upload, _ := client.CreateMultipartUpload(&input)
    uploadPartInput := s3.UploadPartInput{
        Bucket:     aws.String(bucket),
        Key:        aws.String(key),
        PartNumber: aws.Int64(int64(1)),
        UploadId:   upload.UploadId,
        Body:          content,
    }
    var completedParts []*s3.CompletedPart
    completedPart, _ := client.UploadPart(&uploadPartInput)
    completedParts = append(completedParts, &s3.CompletedPart{
        ETag:       completedPart.ETag,
        PartNumber: aws.Int64(int64(1)),
    })
    completeMPUInput := s3.CompleteMultipartUploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
        MultipartUpload: &s3.CompletedMultipartUpload{
            Parts: completedParts,
        },
        UploadId: upload.UploadId,
    }
    d, _ := client.CompleteMultipartUpload(&completeMPUInput)
    fmt.Println(d)
}

Key Protect verwenden

Key Protect kann zu einem Speicherbucket zum Verwalten von Verschlüsselungsschlüsseln hinzugefügt werden. Alle Daten werden unter IBM Cloud Object Storage verschlüsselt, doch Key Protect bietet einen Dienst zur Generierung, Rotation und Zugriffskontrolle von Verschlüsselungsschlüsseln über einen zentralisierten Dienst an.

Vorbereitende Schritte

Die folgenden Elemente sind erforderlich, um einen Bucket mit aktivierter Key-Protect-Funktion zu erstellen:

Cloudressourcenname für Stammschlüssel abrufen

  1. Rufen Sie die Instanz-ID für den Key Protect-Service ab.
  2. Verwenden Sie die Key Protect-API, um alle verfügbaren Schlüssel abzurufen.
    • Sie können entweder curl-Befehle oder einen API-REST-Client wie zum Beispiel Postman für den Zugriff auf die Key Protect-API verwenden.
  3. Rufen Sie die CRN des Stammschlüssels ab, den Sie zur Aktivierung von „ Key Protect “ für Ihren Bucket verwenden. Das CRN sieht in etwa wie folgt aus:

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

Bucket während Aktivierung von Key Protect erstellen

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

Schlüsselwerte

  • <NEW_BUCKET_NAME>- Der Name des neuen Buckets.
  • <ROOT-KEY-CRN>- CRN des Root-Schlüssels, der über den Dienst „ Key Protect “ abgerufen wurde.
  • <ALGORITHM>- Der Verschlüsselungsalgorithmus, der für neue Objekte verwendet wird, die dem Bucket hinzugefügt werden (Standard ist „ AES256 “).

Übertragungsmanager verwenden

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

Erweiterte Liste abrufen

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

Schlüsselwerte

  • <MAX_KEYS>- Maximale Anzahl der Buckets, die in der Anfrage abgerufen werden sollen.
  • <MARKER>- Der Name des Buckets, bei dem die Auflistung beginnen soll (bis zu diesem Bucket überspringen).
  • <PREFIX- Es sollen nur Buckets berücksichtigt werden, deren Name mit diesem Präfix beginnt.

Erweiterte Liste mit Seitenaufteilung abrufen

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

Schlüsselwerte

  • <MAX_KEYS>- Maximale Anzahl der Buckets, die in der Anfrage abgerufen werden sollen.
  • <MARKER>- Der Name des Buckets, bei dem die Auflistung beginnen soll (bis zu diesem Bucket überspringen).
  • <PREFIX- Es sollen nur Buckets berücksichtigt werden, deren Name mit diesem Präfix beginnt.

Schichtunterstützung archivieren

Sie können Objekte automatisch nach einem angegebenen Zeitraum oder nach einem angegebenen Datum archivieren. Nach der Archivierung kann eine temporäre Kopie eines Objekts nach Bedarf für den Zugriff wiederhergestellt werden.

Die Wiederherstellung der temporären Kopie eines oder mehrerer Objekte kann bis zu 12 Stunden in Anspruch nehmen.

Um das angegebene Beispiel zu verwenden, geben Sie Ihre eigene Konfiguration ein, einschließlich des Ersetzens von <apikey> und anderer eingeklammerter <...> Informationen, wobei Sie bedenken sollten, dass die Verwendung von Umgebungsvariablen sicherer ist und Sie keine Anmeldeinformationen in Code eingeben sollten, der versioniert wird.

Eine Archivierungsrichtlinie wird auf Bucketebene festgelegt, indem die Methode PutBucketLifecycleConfiguration für eine Clientinstanz aufgerufen wird. Eine neu hinzugefügte oder geänderte Archivierungsrichtlinie gilt für neu hochgeladene Objekte, wirkt sich jedoch auf bereits vorhandene Objekte nicht aus.

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

Hier wird die typische Antwort veranschaulicht.

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

Immutable Object Storage (IOS)

Benutzer können Buckets mit der Richtlinie Immutable Object Storage konfigurieren, um zu verhindern, dass Objekte für einen bestimmten Zeitraum geändert oder gelöscht werden. Der Aufbewahrungszeitraum kann auf Objektbasis angegeben werden oder Objekte können einen Standardaufbewahrungszeitraum für das Bucket übernehmen. Es ist auch möglich, offene und permanente Aufbewahrungsfristen festzulegen. Unveränderlicher Object Storage entspricht den Regeln, die von der SEC für die Aufbewahrung von Datensätzen festgelegt werden, und IBM Cloud-Administratoren können diese Einschränkungen nicht umgehen.

Immutable Object Storage unterstützt zum jetzigen Zeitpunkt keine Aspera Übertragungen über das SDK, um Objekte oder Verzeichnisse hochzuladen.

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

Hier wird die typische Antwort veranschaulicht.

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

Erstellen einer gehosteten statischen Website

Für diese Operation sind Berechtigungen erforderlich, da nur der Bucketeigner normalerweise berechtigt ist, ein Bucket zum Hosten einer statischen Website zu konfigurieren. Die Parameter bestimmen das Standardsuffix für Besucher der Site sowie ein optionales Fehlerdokument, das hier enthalten ist, um das Beispiel zu vervollständigen.

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
}

Erstellen einer Sicherungsrichtlinie

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

Auflistung einer Sicherungsrichtlinie

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

Erstellen Sie eine Backup-Richtlinie

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

Löschen einer Sicherungsrichtlinie

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

Erstellen eines Backup Tresors

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

Auflistung von Backup-Tresoren

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

Backup-Tresore erhalten

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

Backup-Tresore aktualisieren

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

Löschen eines Sicherungsdepots

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

Auflistung der Verwertungsspannen

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

Erholungsbereich erhalten

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

Wiederherstellungsbereiche aktualisieren

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

Initiieren einer Wiederherstellung

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

Auflistung Wiederherstellen

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

Details zur Wiederherstellung abrufen

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

Erstellen eines neuen Cloud Object Storage Buckets mit aktivierter Objektsperre

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

Setzen Sie die Objektsperrkonfiguration mit dem Übereinstimmungsmodus auf 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)
}

Konfiguration der Objektsperre mit Governance-Modus auf Cloud Object Storage bucket setzen

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

Abrufen der Objektsperrkonfiguration auf 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)
    }
}

Hochladen eines Objekts mit Governance-Modus in den Cloud Object Storage Bucket

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

Objektsperre mit Compliance-Modus auf das Objekt setzen

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

Objektsperre mit Governance-Modus auf das Objekt anwenden

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

Objektsperre beibehalten

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

Objekt sperren – Legal Hold

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

Objektsperre „Legal Hold“ setzen

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

Löschen eines Objekts mit Objektsperren-Governance-Modus, der Bypass-Governance verwendet

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

Nächste Schritte

Falls Sie es noch nicht getan haben, lesen Sie die ausführliche Klassen- und Methodendokumentation in der Go-API-Dokumentation.