Um bucket é o contêiner principal do OSS para armazenar objetos. Ele tem capacidade ilimitada e escala de forma elástica.
Configuração básica
As configurações principais de um bucket não podem ser alteradas após a criação.
Nome do bucket: Deve ser globalmente único. Utilize um nome que reflita seu departamento ou negócio para facilitar a identificação. Exemplo:
hr-documents.-
Região: Determina a localização física dos seus dados. Selecione uma região com base nestas prioridades:
Conformidade: Selecione uma região que atenda aos seus requisitos regulatórios.
Desempenho: Selecione a região mais próxima dos seus usuários finais. Se seus dados forem acessados por produtos da Alibaba Cloud, como ECS, selecione a mesma região para utilizar a rede interna gratuita e reduzir a latência.
Suporte a recursos: Consulte o Release notes para confirmar que a região oferece suporte aos recursos necessários.
Custo: Após satisfazer os requisitos anteriores, escolha uma região com custos menores.
NotaNão é possível criar novos buckets na região China (Zhangjiakou). Os buckets existentes nessa região continuam totalmente funcionais. Se você tiver um plano de recursos para essa região, ele ainda poderá ser usado para compensar os custos dos seus buckets existentes.
Se você especificar apenas o nome e a região do bucket, o OSS aplicará os seguintes padrões: classe de armazenamento Standard, Zone-Redundant Storage (ZRS), ACL privada e Block Public Access ativado.
Console
Na página Buckets do console do OSS, clique em Create Bucket.
No painel Create Bucket, defina o Bucket Name e a Region e, em seguida, clique em Create na parte inferior.
ossutil
Crie buckets pela linha de comando. Install ossutil.
-
Configure a região do bucket.
ossutil config -
Pressione Enter para pular as configurações anteriores até que o prompt de região apareça:
Please enter Region [cn-hangzhou]:Insira um ID de região (por exemplo,
cn-beijing) e pressione Enter, ou pressione Enter para usar o padrão (cn-hangzhou). IDs de região disponíveis: OSS Region List. -
Crie um bucket chamado
examplebucket.ossutil mb oss://examplebucket -
Verifique se o bucket foi criado com sucesso.
ossutil ls
Sintaxe completa do comando e opções:mb (create a bucket).
SDK
Os exemplos de código a seguir criam um bucket com os SDKs mais comuns. Outros SDKs estão cobertos em SDK introduction.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class Demo {
public static void main(String[] args) throws Exception {
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name.
String bucketName = "examplebucket";
// Specify the resource group ID. If you do not specify a resource group ID, the bucket is added to the default resource group.
//String rsId = "rg-aek27tc****";
// Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// After an OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a bucket and enable the hierarchical namespace feature.
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
// If you want to specify the storage class, ACL, and data redundancy type when you create a bucket, see the following code.
// The following code provides an example of how to set the storage class to Standard.
createBucketRequest.setStorageClass(StorageClass.Standard);
// The default data redundancy type is LRS, which is specified as DataRedundancyType.LRS. If you want to set the data redundancy type to ZRS, set the value to DataRedundancyType.ZRS.
createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
// Set the ACL of the bucket to public-read. The default ACL is private.
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
// When you create a bucket in a region that supports resource groups, you can assign the bucket to a resource group.
//createBucketRequest.setResourceGroupId(rsId);
// Create the bucket.
ossClient.createBucket(createBucketRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}import argparse
import alibabacloud_oss_v2 as oss
# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put bucket sample")
# Specify the required command line parameter --region, which specifies the region in which the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the required command line parameter --bucket, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the optional command line parameter --endpoint, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
args = parser.parse_args() # Parse command line parameters.
# Load access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located.
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance.
client = oss.Client(cfg)
# Execute the request to create a bucket and set its storage class to Standard.
result = client.put_bucket(oss.PutBucketRequest(
bucket=args.bucket,
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='Standard'
)
))
# Output the HTTP status code in the response and the request ID used to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
if __name__ == "__main__":
main() # Entry point of the script. The main function is invoked when the file is run directly.package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string
bucketName string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
flag.Parse()
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load default config. Credentials are read from environment variables.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
request := &oss.PutBucketRequest{
Bucket: oss.Ptr(bucketName),
}
// Create the bucket.
result, err := client.PutBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket %v", err)
}
log.Printf("put bucket result:%#v\n", result)
}<?php
// Automaticically load objects and dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region parameter is required. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket is required.
];
// Generate a list of long options for parsing command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));
// Parse command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters have been configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
exit(1);
}
}
// Retrieve the values of the command line parameters.
$region = $options["region"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the bucket.
// Load the credential information (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a request to initiate bucket creation.
$request = new Oss\Models\PutBucketRequest($bucket);
// Call the putBucket method.
$result = $client->putBucket($request);
// Output the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP status code.
'request id:' . $result->requestId // Unique ID of the request.
);
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Create a bucket.
try
{
var request = new CreateBucketRequest(bucketName);
// Set the access control list (ACL) to public-read. The default ACL is private.
request.ACL = CannedAccessControlList.PublicRead;
// Set the data disaster recovery type to zone-redundant storage.
request.DataRedundancyType = DataRedundancyType.ZRS;
client.CreateBucket(request);
Console.WriteLine("Create bucket succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Create bucket failed. {0}", ex.Message);
}const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourBucketName',
});
// Create the bucket.
async function putBucket() {
try {
const options = {
storageClass: 'Standard', // By default, the storage class of a bucket is Standard. To set the storage class of the bucket to Archive, set storageClass to Archive.
acl: 'private', // By default, the access control list (ACL) of a bucket is private. To set the ACL of the bucket to public read, set acl to public-read.
dataRedundancyType: 'LRS' // By default, the redundancy type of a bucket is locally redundant storage (LRS). To set the redundancy type of the bucket to zone-redundant storage (ZRS), set dataRedundancyType to ZRS.
}
// Specify the name of the bucket.
const result = await client.putBucket('examplebucket', options);
console.log(result);
} catch (err) {
console.log(err);
}
}
putBucket(); require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual one.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# 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.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. Example: examplebucket.
client.create_bucket('examplebucket')// Construct a request to create a bucket.
// Specify the bucket name.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("examplebucket");
// Specify the access control list (ACL) of the bucket.
// createBucketRequest.setBucketACL(CannedAccessControlList.Private);
// Specify the storage class of the bucket.
// createBucketRequest.setBucketStorageClass(StorageClass.Standard);
// Create the bucket asynchronously.
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
@Override
public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
Log.d("asyncCreateBucket", "Success");
}
@Override
public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
// Request exception.
if (clientException != null) {
// Client-side exceptions, such as network errors.
clientException.printStackTrace();
}
if (serviceException != null) {
// Server-side exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});// Construct a request to create a bucket.
OSSCreateBucketRequest * create = [OSSCreateBucketRequest new];
// Set the bucket name to examplebucket.
create.bucketName = @"examplebucket";
// Set the access control list (ACL) of the bucket to private.
create.xOssACL = @"private";
// Set the storage class of the bucket to Infrequent Access (IA).
create.storageClass = OSSBucketStorageClassIA;
OSSTask * createTask = [client createBucket:create];
[createTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"create bucket success!");
} else {
NSLog(@"create bucket failed, error: %@", task.error);
}
return nil;
}];
// Block the current thread to wait for the task to complete.
// [createTask waitUntilFinished]; #include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specifies whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* At the program entry point, call the aos_http_io_initialize method to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
oss_acl_e oss_acl = OSS_ACL_PRIVATE;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* data to the aos_string_t bucket. */
aos_str_set(&bucket, bucket_name);
/* Create the bucket. */
resp_status = oss_create_bucket(oss_client_options, &bucket, oss_acl, &resp_headers);
/* Check whether the request was successful. */
if (aos_status_is_ok(resp_status)) {
printf("create bucket succeeded\n");
} else {
printf("create bucket failed\n");
}
/* Release the memory pool. This releases the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}API
Ao chamar a operação PutBucket, especifique o nome do bucket e a região no cabeçalho de requisição Host.
Classe de armazenamento
O OSS oferece cinco storage classes: Standard, Infrequent Access (IA), Archive, Cold Archive e Deep Cold Archive. O padrão é Standard. Cada nível inferior reduz o custo de armazenamento, mas adiciona restrições de acesso.
Os objetos herdam a classe de armazenamento do bucket. Não é possível alterar a classe de armazenamento de um bucket após a criação, mas regras lifecycle podem fazer a transição automática de objetos para níveis de menor custo.
-
Standard
Ideal para dados ativos acessados mais de uma vez por mês, com acesso em tempo real. Escolha Standard se você não tiver certeza sobre os padrões de acesso — utilize regras de ciclo de vida posteriormente para fazer a transição dos objetos para níveis de menor custo.
-
Infrequent Access (IA):
Adequado para dados mornos acessados mensalmente ou com menos frequência (backups, logs). Acesso em tempo real, duração mínima de armazenamento de 30 dias. A exclusão antecipada gera cobranças pela duração total. Não indicado para dados temporários ou de teste.
-
Archive:
Destinado a dados frios acessados menos de uma vez a cada 90 dias. Suporta acesso em tempo real via leitura direta de archive ou restauração antes da leitura (~1 minuto). Duração mínima de armazenamento: 60 dias.
Restauração: tornar dados arquivados temporariamente legíveis após um período de espera.
-
Cold Archive
Projetado para dados acessados menos de uma vez por ano. Requer restauração (1–12 horas) antes da leitura. Custo reduzido, duração mínima de armazenamento de 180 dias.
-
Deep Cold Archive
O nível de menor custo, para dados acessados menos de uma vez por ano. A restauração leva 12 ou 48 horas, com duração mínima de armazenamento de 180 dias. Não defina este como a classe de armazenamento padrão para novos buckets. Em vez disso, utilize regras de ciclo de vida para fazer a transição dos dados para este nível.
Console
Selecione a classe de armazenamento durante a criação do bucket.
ossutil
Crie um bucket chamado examplebucket com a classe de armazenamento IA:
ossutil mb oss://examplebucket --storage-class IA
Sintaxe completa do comando e opções:mb (create a bucket).
OSS SDK
Os exemplos de código a seguir criam um bucket com os SDKs mais comuns. Outros SDKs estão cobertos em SDK introduction.
Java
Para definir a classe de armazenamento, configure o objeto CreateBucketRequest conforme mostrado a seguir.
// Prepare a request object that contains the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setStorageClass(StorageClass.IA); // Specify the storage class here.
// Options: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
Exemplo completo:Create a bucket (Java SDK V1).
Python
Ao chamar o método client.put_bucket, especifique a classe de armazenamento usando o parâmetro create_bucket_configuration.
# Prepare a request object that contains the storage class.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
storage_class='IA' # Specify the storage class here.
)
)
# Options: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
Exemplo completo:Create a bucket (Python SDK V2).
Go
Para definir a classe de armazenamento, configure o campo CreateBucketConfiguration ao criar um PutBucketRequest.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
StorageClass: oss.StorageClassIA, // Specify the storage class here.
},
}
// Options: oss.StorageClassStandard, oss.StorageClassIA, oss.StorageClassArchive, etc.
Exemplo completo:Create a bucket (Go SDK V2).
PHP
Para definir a classe de armazenamento, passe um objeto CreateBucketConfiguration ao construtor ao criar um objeto PutBucketRequest.
// Prepare a request object that contains configurations such as the storage class.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA' // Specify the storage class here.
)
);
/*
* Optional storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
*/
Exemplo completo:Create a bucket (PHP SDK V2).
C#
Para definir a classe de armazenamento, crie um objeto CreateBucketRequest e configure suas propriedades conforme mostrado a seguir.
// Prepare a request object that contains the storage class configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.StorageClass = StorageClass.IA; // Specify the storage class here.
// Optional storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
Exemplo completo:Create a bucket (C# SDK V1).
Node.js
Para definir a classe de armazenamento, crie um objeto options e passe-o ao método putBucket.
// Prepare an options object that contains the storage class configuration.
const options = {
storageClass: 'IA', // Specify the storage class here.
};
// Optional storage classes: 'Standard', 'IA', 'Archive', 'ColdArchive', 'DeepColdArchive'
Exemplo completo:Create a bucket (Node.js SDK).
Android
Para definir a classe de armazenamento ou a lista de controle de acesso, crie um objeto CreateBucketRequest e configure-o conforme mostrado a seguir.
// Prepare a request object that contains configurations such as the storage class.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketStorageClass(StorageClass.IA); // Specify the storage class here.
// Optional storage classes: StorageClass.Standard, StorageClass.IA, StorageClass.Archive, etc.
Exemplo completo:Create a bucket (Android SDK).
iOS
Para definir a classe de armazenamento, crie um objeto OSSCreateBucketRequest e configure suas propriedades conforme mostrado a seguir.
// Prepare a request object that contains configurations such as the storage class.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.storageClass = OSSBucketStorageClassIA; // Specify the storage class here.
// Optional storage classes: OSSBucketStorageClassStandard, OSSBucketStorageClassIA, etc.
Exemplo completo:Create a bucket (iOS SDK).
API
Ao chamar PutBucket, especifique a classe de armazenamento do bucket no elemento de requisição StorageClass.
Tipo de redundância de armazenamento
Controla a durabilidade, a disponibilidade e a recuperação de desastres dos dados. Padrão: ZRS. É possível upgrade de LRS para ZRS, mas não é possível fazer o downgrade.
-
Zone-Redundant Storage (ZRS) - Recomendado para ambientes de produção
Armazena dados em múltiplas zonas de disponibilidade (AZs) na mesma região, garantindo a continuidade dos negócios mesmo que uma AZ inteira falhe.
-
Locally Redundant Storage (LRS) - Para dados não críticos ou de teste
Armazena dados com redundância dentro de uma única AZ a um custo menor. Protege contra falhas de hardware, mas não garante acesso caso a AZ inteira fique indisponível.
Console
Selecione o tipo de redundância ao criar o bucket.
ossutil
Crie um bucket chamado examplebucket com redundância LRS:
ossutil mb oss://examplebucket --redundancy-type LRS
Sintaxe completa do comando e opções: mb (create a bucket).
OSS SDK
Java
Para definir o tipo de redundância de armazenamento, configure o objeto CreateBucketRequest conforme indicado abaixo.
// Prepare a request object that contains the storage redundancy type.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS); // Specify the storage redundancy type here.
// Options: DataRedundancyType.ZRS, DataRedundancyType.LRS
Exemplo completo: Create a bucket (Java SDK V1).
Python
Ao chamar o método client.put_bucket, use o parâmetro create_bucket_configuration para especificar o tipo de redundância de armazenamento.
# Prepare a request object that contains the storage redundancy type.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
data_redundancy_type='ZRS' # Specify the storage redundancy type here.
)
)
# Options: 'ZRS', 'LRS'
Exemplo completo: Create a bucket (Python SDK V2).
Go
Para definir o tipo de redundância de armazenamento, configure o campo CreateBucketConfiguration ao criar um PutBucketRequest.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
DataRedundancyType: oss.DataRedundancyZRS, // Specify the storage redundancy type here.
},
}
// Options: oss.DataRedundancyZRS, oss.DataRedundancyLRS
Exemplo completo: Create a bucket (Go SDK V2).
PHP
Para definir o tipo de redundância de armazenamento, passe um objeto CreateBucketConfiguration ao construtor ao criar um objeto PutBucketRequest.
// Prepare a request object that contains configurations such as the storage redundancy type.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
null, // acl
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
null, // storageClass
'ZRS' // Specify the storage redundancy type here.
)
);
/*
* Optional storage redundancy types: 'ZRS', 'LRS'
*/
Exemplo completo: Create a bucket (PHP SDK V2).
C#
Para definir o tipo de redundância de armazenamento, crie um objeto CreateBucketRequest e configure suas propriedades conforme indicado abaixo.
// Prepare a request object that contains the storage redundancy type configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.DataRedundancyType = DataRedundancyType.ZRS; // Specify the storage redundancy type here.
// Optional storage redundancy types: DataRedundancyType.ZRS, DataRedundancyType.LRS
Exemplo completo: Create a bucket (C# SDK V1).
Node.js
Para definir o tipo de redundância de armazenamento, crie um objeto options e passe-o ao método putBucket.
// Prepare an options object that contains the storage redundancy type configuration.
const options = {
dataRedundancyType: 'LRS', // Specify the storage redundancy type here.
};
// Optional storage redundancy types: 'ZRS', 'LRS'
Exemplo completo: Create a bucket (Node.js SDK).
API
Ao chamar PutBucket, especifique o tipo de redundância de armazenamento do bucket no elemento de requisição DataRedundancyType.
Lista de controle de acesso (ACL)
A ACL controla o acesso a um bucket e aos seus objetos. O padrão é privado e pode ser alterado após a criação. Os objetos herdam a ACL do bucket, ou você pode set permissions for individual objects.
-
Privado - Altamente recomendado
Padrão e mais seguro. Apenas o proprietário do bucket e usuários explicitamente autorizados (via RAM ou políticas de bucket) podem acessar o bucket. Recomendado para todos os casos de uso. Conceda acesso a terceiros por meio de Overview of permissions and access control.
-
Leitura pública - Use com cautela
Qualquer pessoa pode ler objetos sem autenticação.
Os dados ficam totalmente públicos, o que pode gerar cobranças inesperadas de tráfego de saída. Use apenas para conteúdo público, como ativos de sites estáticos.
Se a leitura pública for necessária, configure hotlink protection para restringir o acesso a referenciadores específicos e evitar tráfego não autorizado.
-
Leitura/gravação pública - Fortemente desaconselhado
Qualquer pessoa pode ler, gravar e excluir objetos. Risco de segurança extremo com potencial para cobranças substanciais. Use apenas em casos especiais, como repositórios públicos.
Console
Por motivos de segurança, o OSS console ativa o Block Public Access por padrão e permite apenas a criação de buckets privados.
Para definir uma ACL pública:
Clique em o nome do bucket de destino para acessar sua página de detalhes.
No painel de navegação à esquerda, escolha Permissions > Block Public Access e desative esta política.
Alterne para a aba ACL e clique em Configure.
Siga as instruções na tela para alterar a ACL do bucket para Public Read ou Public Read/Write.
ossutil
Crie um bucket chamado examplebucket com ACL privada:
ossutil mb oss://examplebucket --acl=private
Sintaxe completa do comando e opções: mb (create a bucket).
OSS SDK
Java
Para definir a lista de controle de acesso, configure o objeto CreateBucketRequest conforme indicado abaixo.
// Prepare a request object that contains the access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setCannedACL(CannedAccessControlList.Private); // Specify the bucket ACL here.
// Options: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
Exemplo completo: Create a bucket (Java SDK V1).
Python
Ao chamar o método client.put_bucket, especifique a lista de controle de acesso no parâmetro create_bucket_configuration.
# Prepare a request object that contains the access permissions.
req = oss.PutBucketRequest(
bucket="your-bucket-name",
create_bucket_configuration=oss.CreateBucketConfiguration(
access_control_policy='private' # Specify the access permissions here.
)
)
# Options: 'private', 'public-read', 'public-read-write'
Exemplo completo: Create a bucket (Python SDK V2).
Go
Para definir a lista de controle de acesso, configure o campo Acl ao criar um PutBucketRequest.
// Prepare a request object that contains configurations such as access permissions.
request := &oss.PutBucketRequest{
Bucket: oss.Ptr("your-bucket-name"),
Acl: oss.BucketACLPrivate, // Specify the access permissions here.
CreateBucketConfiguration: &oss.CreateBucketConfiguration{
},
}
// Optional access permissions: oss.BucketACLPrivate, oss.BucketACLPublicRead, oss.BucketACLPublicReadWrite
Exemplo completo: Create a bucket (Go SDK V2).
PHP
Para definir a lista de controle de acesso, configure o campo Acl ao criar um PutBucketRequest.
// Prepare a request object that contains configurations such as access permissions.
$request = new Oss\Models\PutBucketRequest(
"your-bucket-name",
'private', // Specify the access permissions here (second parameter).
null, // resourceGroupId
new Oss\Models\CreateBucketConfiguration(
'IA', // Specify the storage class here.
'ZRS' // Specify the redundancy type here.
)
);
/*
* Optional access permissions: 'private', 'public-read', 'public-read-write'
*/
Exemplo completo: Create a bucket (PHP SDK V2).
C#
Para definir a lista de controle de acesso, crie um objeto CreateBucketRequest e configure suas propriedades conforme indicado abaixo.
// Prepare a request object that contains the access permission configuration.
var request = new CreateBucketRequest("your-bucket-name");
request.ACL = CannedAccessControlList.Private; // Specify the access permissions here.
// Optional access permissions: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
Exemplo completo: Create a bucket (C# SDK V1).
Node.js
Para definir as permissões de acesso, crie um objeto options e passe-o ao método putBucket.
// Prepare an options object that contains the access permissions.
const options = {
acl: 'private', // Specify the access permissions here.
};
// Optional access permissions: 'private', 'public-read', 'public-read-write'
Exemplo completo: Create a bucket (Node.js SDK).
Android
Para definir a lista de controle de acesso, crie um objeto CreateBucketRequest e configure-o conforme indicado abaixo.
// Prepare a request object that contains configurations such as access permissions.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("your-bucket-name");
createBucketRequest.setBucketACL(CannedAccessControlList.Private); // Specify the access permissions here.
// Optional access permissions: CannedAccessControlList.Private, CannedAccessControlList.PublicRead, CannedAccessControlList.PublicReadWrite
Exemplo completo: Create a bucket (Android SDK).
iOS
Para definir as permissões de acesso, crie um objeto OSSCreateBucketRequest e configure suas propriedades conforme indicado abaixo.
// Prepare a request object that contains configurations such as access permissions.
OSSCreateBucketRequest *create = [OSSCreateBucketRequest new];
create.bucketName = @"your-bucket-name";
create.xOssACL = @"private"; // Specify the access permissions here.
// Optional access permissions: private, public-read, public-read-write, etc.
Exemplo completo: Create a bucket (iOS SDK).
API
Ao chamar PutBucket, especifique as permissões do bucket no cabeçalho de requisição x-oss-acl.
Block Public Access
Chave de segurança global que impede a exposição não intencional de dados decorrente de ACLs ou políticas de bucket mal configuradas.
Quando ativado, apenas buckets privados podem ser criados e ACLs ou políticas públicas são bloqueadas. Habilitado por padrão. É possível desativá-lo após a criação, mas manter a opção ativada é fortemente recomendado.
Recursos opcionais
Configure esses recursos conforme necessário durante ou após a criação do bucket.
-
Versionamento
Evita a perda acidental de dados. Ao fazer upload de um objeto com o mesmo nome, uma nova versão é criada em vez de sobrescrever o original. Restaure qualquer versão anterior para se recuperar de erros. Versioning.
-
Criptografia do lado do servidor
Criptografa dados em repouso automaticamente — o OSS criptografa na gravação e descriptografa na leitura. Ative pelo menos a opção gerenciada pelo OSS. Server-side encryption.
-
Grupo de recursos
Agrupe buckets por departamento ou projeto para gerenciamento de permissões e contabilidade de custos separados. Use resource groups.
-
Consulta de log em tempo real
Consulte e analise logs de acesso ao bucket no console. Rastreie quem acessou quais objetos e quando, para investigar atividades incomuns ou analisar o uso. Real-time log query.
-
Backup agendado
Automatiza o backup de dados em um cronograma definido. Configure scheduled backup for a bucket.
-
OSS-HDFS service
Permite que frameworks de big data, como o Spark, analisem dados no OSS diretamente, sem necessidade de migração. What is the OSS-HDFS service?
-
Tag de bucket
Classifique buckets com tags de chave-valor, como
Department:R&D, para gerenciamento em lote e análise de custos. Manage bucket tags.
Faturamento
A criação de um bucket é gratuita. As cobranças são baseadas no uso real de armazenamento. Para evitar custos desnecessários:
Compatibilidade com planos de recursos O tipo do seu plano de recursos deve corresponder ao tipo de redundância de armazenamento do bucket. Um plano de recursos LRS não pode compensar custos de buckets ZRS, e vice-versa.
-
Faturamento especial para classes de armazenamento não Standard IA, Archive, Cold Archive e Deep Cold Archive oferecem preços unitários menores, mas impõem durações mínimas de armazenamento e data retrieval fees.
Exclusão ou modificação antecipada: se você excluir ou modificar um objeto antes do término da duração mínima de armazenamento, será cobrado pela duração mínima completa.
Leitura de dados: acessar dados em qualquer classe de armazenamento diferente de Standard gera uma taxa adicional de recuperação de dados.
Riscos do acesso público Definir a ACL como leitura pública ou leitura/gravação pública expõe os dados à internet, gerando risco de hotlinking não autorizado e cobranças de tráfego inesperadamente altas.