Este tópico descreve como listar buckets que atendem a condições específicas em todas as regiões da conta atual.
Observações de uso
O código de exemplo deste tópico usa o ID da região China (Hangzhou)
cn-hangzhou. Por padrão, o sistema usa um endpoint público. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints.Listar buckets exige a permissão
oss:ListBuckets. Para obter mais informações, consulte Conceder políticas de acesso personalizadas a usuários do RAM.-
Ao usar um SDK para listar buckets, especifique um ID de grupo de recursos para filtrar os buckets de um grupo específico.
Por padrão, ao listar buckets via SDK, a requisição não inclui o parâmetro de ID do grupo de recursos e a resposta em formato XML não contém informações sobre grupos de recursos.
Se você especificar o parâmetro de ID do grupo de recursos na requisição, o OSS retornará todos os buckets pertencentes a esse grupo.
Caso a requisição não especifique o parâmetro de ID do grupo de recursos, o OSS retornará todos os buckets de propriedade do solicitante.
Listar buckets de uma conta em todas as regiões
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Import the autoloader file to load dependency libraries.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command line argument descriptions.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region must be specified. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional. The endpoint that other services can use to access OSS.
];
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check whether all 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"; // A message is displayed, indicating that a required parameter is missing.
exit(1);
}
}
// Retrieve the values of the command line arguments.
$region = $options["region"]; // The region where the bucket is located.
// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load credentials from environment variables.
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault(); // Load the default configurations of the SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a paginator for the ListBuckets operation.
$paginator = new Oss\Paginator\ListBucketsPaginator($client); // Create a paginator to list buckets.
$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest()); // Retrieve the pagination iterator.
// Traverse the paginated results.
foreach ($iter as $page) { // Traverse the list of buckets on each page.
foreach ($page->buckets ?? [] as $bucket) { // Traverse each bucket on the current page.
print ("Bucket: $bucket->name, $bucket->location\n"); // Print the bucket name and its region.
}
}
Listar todos os buckets em um grupo de recursos específico
Por padrão, ao listar buckets via SDK, a requisição não inclui o parâmetro de ID do grupo de recursos e a resposta em formato XML não contém informações sobre grupos de recursos.
Quando uma requisição especifica o parâmetro de ID do grupo de recursos, o OSS retorna todos os buckets desse grupo.
Se a requisição não especificar o parâmetro de ID do grupo de recursos, o OSS retornará todos os buckets de propriedade do solicitante.
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Import the autoloader file to load dependency libraries.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command line argument descriptions.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region must be specified. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional. The endpoint that other services can use to access OSS.
];
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check whether all 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"; // A message is displayed, indicating that a required parameter is missing.
exit(1);
}
}
// Retrieve the values of the command line arguments.
$region = $options["region"]; // The region where the bucket is located.
// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load credentials from environment variables.
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault(); // Load the default configurations of the SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a paginator for the ListBuckets operation.
$paginator = new Oss\Paginator\ListBucketsPaginator($client); // Create a paginator to list buckets.
$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest(
resourceGroupId: "rg-aekzfalvmw2sxby", // List buckets in the specified resource group.
));
// Traverse the paginated results.
foreach ($iter as $page) { // Traverse the list of buckets on each page.
foreach ($page->buckets ?? [] as $bucket) { // Traverse each bucket on the current page.
print ("Bucket: $bucket->name, $bucket->location\n"); // Print the bucket name and its region.
}
}
Referências
Para obter o código de exemplo completo de listagem de buckets, consulte o exemplo no GitHub.
Para obter mais informações sobre a operação de API usada para listar buckets, consulte ListBuckets (GetService).