Este tema describe cómo crear un inventario para un bucket y cómo consultar, listar y eliminar los inventarios configurados en un bucket.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Asegúrese de contar con los permisos necesarios para crear, consultar, listar y eliminar inventarios de un bucket. De forma predeterminada, el propietario del bucket tiene los permisos para ejecutar estas operaciones. Si no cuenta con dichos permisos, solicite al propietario del bucket que se los otorgue.
Se pueden configurar hasta 1,000 inventarios por bucket.
El bucket de origen, para el cual desea configurar un inventario, debe desplegarse en la misma región que el bucket de destino donde se almacenará la lista de inventario.
Crear un inventario para un bucket
A continuación se muestra un ejemplo de código para crear un inventario en un bucket:
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
IsEnabled := true
// The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) managed by Key Management Service (KMS).
//var invEncryption oss.InvEncryption
//var invSseOss oss.InvSseOss
//var invSseKms oss.InvSseKms
//invSseKms.KmsId = "<yourKmsId>" // Specify the ID of CMK that is managed by KMS.
//invEncryption.SseOss = &invSseOss // Use OSS-managed keys (SSE-OSS) to encrypt the inventory lists.
//invEncryption.SseKms = &invSseKms // Use CMKs managed by KMS (SSE-KMS) to encrypt inventory lists.
invConfig := oss.InventoryConfiguration{
// Specify the name of the inventory. The name must be globally unique in the current bucket.
Id: "yourInventoryId2",
// Enable the inventory.
IsEnabled: &IsEnabled,
// Specify the rule that is used to filter the objects included in inventories. The following code provides an example on how to filter the objects by prefix.
Prefix: "yourFilterPrefix",
OSSBucketDestination: oss.OSSBucketDestination{
// Specify the format of the exported inventory lists.
Format: "CSV",
// Specify the ID of the account that is granted permissions by the bucket owner to perform the operation. Example: 109885487000****.
AccountId: "yourGrantAccountId",
// Specify the name of the RAM role that is granted permissions by the bucket owner to perform the operation. Example: acs:ram::109885487000****:role/ram-test.
RoleArn: "yourRoleArn",
// Specify the name of the bucket in which you want to store the generated inventory lists.
Bucket: "acs:oss:::" + "yourDestBucketName",
// Specify the prefix of the path in which you want to store the generated inventory lists.
Prefix: "yourDestPrefix",
// The following sample code provides an example on how to encrypt inventory lists.
//Encryption: &invEncryption,
},
// Specify the frequency at which inventory lists are exported.
Frequency: "Daily",
// Specify whether to include all versions of objects or only the current versions of objects in the inventory lists.
IncludedObjectVersions: "All",
OptionalFields: oss.OptionalFields{
// Specify the fields that are included in inventory lists.
Field: []string{
"Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
},
},
}
// Specify the name of the bucket for which you want to configure the inventory.
err = client.SetBucketInventory("yourBucketName", invConfig)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Consultar los inventarios de un bucket
A continuación se muestra un ejemplo de código para consultar un inventario configurado en un bucket:
package main
import (
"encoding/xml"
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket
// Specify the name of the inventory.
result, err := client.GetBucketInventory("yourBucketName", "yourInventoryId")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the inventory.
bs, err := xml.MarshalIndent(result, " ", " ")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println(string(bs))
}
Listar varios inventarios a la vez
Es posible consultar hasta 100 inventarios en una sola solicitud. Para consultar más de 100 inventarios, envíe varias solicitudes y utilice el token devuelto en cada solicitud como parámetro para la siguiente.
A continuación se muestra un ejemplo de código para listar los inventarios configurados en un bucket:
package main
import (
"encoding/xml"
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var sumResult oss.ListInventoryConfigurationsResult
vmarker := ""
for {
// Specify the name of the bucket
listResult, err := client.ListBucketInventory("yourBucketName", vmarker)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
sumResult.InventoryConfiguration = append(sumResult.InventoryConfiguration, listResult.InventoryConfiguration...)
if listResult.IsTruncated != nil && *listResult.IsTruncated {
vmarker = listResult.NextContinuationToken
} else {
break
}
}
// Display the inventories of the bucket.
bs, err := xml.MarshalIndent(sumResult, " ", " ")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println(string(bs))
}
Eliminar un inventario de un bucket
A continuación se muestra un ejemplo de código para eliminar un inventario configurado en un bucket:
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Delete the inventory.
// Specify the name of the bucket
// Specify the name of the inventory.
err = client.DeleteBucketInventory("yourBucketName", "yourInventoryId")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Referencias
Para consultar el código de ejemplo completo sobre la gestión de inventarios de buckets, visite GitHub.
Para obtener más información sobre la operación de API que permite crear un inventario para un bucket, consulte PutBucketInventory.
Para obtener más información sobre la operación de API que permite consultar un inventario configurado en un bucket, consulte GetBucketInventory.
Para obtener más información sobre la operación de API que permite listar los inventarios configurados en un bucket, consulte ListBucketInventory.
Para obtener más información sobre la operación de API que permite eliminar los inventarios configurados en un bucket, consulte DeleteBucketInventory.