

# 在本地区域中创建目录存储桶
<a name="create-directory-bucket-LZ"></a>

在专用本地区域中，您可以创建目录存储桶来存储和检索特定数据边界中的对象，以有助于满足数据驻留和数据隔离应用场景的要求。S3 目录存储桶是 Local Zones 中唯一支持的存储桶类型，并且包含名为 `LocalZone` 的存储桶位置类型。目录存储桶名称由您提供的基本名称以及包含存储桶位置的可用区 ID 和 `--x-s3` 的后缀组成。可以使用 [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) API 操作获取本地区域 ID 的列表。有关更多信息，请参阅 [目录存储桶命名规则](directory-bucket-naming-rules.md)。

**注意**  
对于 AWS 专用本地区域（专用本地区域）中的所有服务，包括 S3，管理员必须先启用您的 AWS 账户，然后您才能在专用本地区域中创建或访问任何资源。有关更多信息，请参阅 [为本地区域启用账户](opt-in-directory-bucket-lz.md)。
对于数据驻留要求，我们建议仅允许从网关 VPC 端点访问您的存储桶。有关更多信息，请参阅 [来自 VPC 的私有连接](connectivity-lz-directory-buckets.md)。
要将访问权限仅限于本地区域网络边界组内，您可以在 IAM 策略中使用条件键 `s3express:AllAccessRestrictedToLocalZoneGroup`。有关更多信息，请参阅 [对 Local Zones 中的目录存储桶进行身份验证和授权](iam-directory-bucket-LZ.md)。

下面介绍使用 AWS 管理控制台、AWS CLI 和 AWS SDK 在单个本地区域中创建目录存储桶的方法。

## 使用 S3 控制台
<a name="create-directory-bucket-lz-console"></a>

1. 登录到 AWS 管理控制台，然后通过以下网址打开 Amazon S3 控制台：[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。

1. 在页面顶部的导航栏中，选择当前所显示 AWS 区域的名称。接下来，选择要在其中创建目录存储桶的本地区域的父区域。
**注意**  
有关父区域的更多信息，请参阅[Local Zones 中目录存储桶的概念](s3-lzs-for-directory-buckets.md)。

1. 在左侧导航窗格中，选择**存储桶**。

1. 选择**创建存储桶**。

   此时将打开**创建存储桶**页面。

1. 在**常规配置**下，查看将在其中创建存储桶的 AWS 区域。

1.  在**存储桶类型**下，请选择**目录**。
**注意**  
如果您选择的区域不支持目录存储桶，则存储桶类型默认为通用存储桶。要创建目录桶，您必须选择受支持的区域。有关支持目录存储桶的区域列表，请参阅[目录存储桶的区域和可用区端点](s3-express-Regions-and-Zones.md)。
在创建存储桶后，便无法更改存储桶类型。

1. 在**存储桶位置**下，选择要使用的本地区域。
**注意**  
创建存储桶后无法更改本地区域。

1. 在**存储桶位置**下，选中复选框以确认在本地区域中断的情况下，您的数据可能不可用或丢失。
**重要**  
尽管目录存储桶存储在单个 Local Zones 中的多个设备上，但目录存储桶不会跨 Local Zones 冗余存储数据。

1. 对于**存储桶名称**，请输入目录存储桶的名称。

   有关目录存储桶的命名规则的更多信息，请参阅[通用存储桶命名规则](bucketnamingrules.md)。后缀将自动添加到您使用控制台创建目录存储桶时提供的基本名称中。此后缀包括您选择的本地区域的可用区 ID。

   创建存储桶后，便无法更改其名称。
**重要**  
请勿在存储桶名称中包含敏感信息，如账号。存储桶名称会显示在指向存储桶中的对象的 URL 中。

1. 在**对象所有权**下，将自动启用**强制桶拥有者**设置，并禁用所有访问控制列表（ACL）。对于目录存储桶，ACL 已禁用且无法启用。

   在启用**强制存储桶拥有者**设置的情况下，存储桶拥有者会自动拥有并完全控制存储桶中的每个对象。ACL 不再影响对 S3 存储桶中数据的访问权限。存储桶专门使用策略来定义访问控制。Amazon S3 中的大多数现代使用案例不再需要使用 ACL。有关更多信息，请参阅 [为您的存储桶控制对象所有权和禁用 ACL。](about-object-ownership.md)。

1. 在**此桶的屏蔽公共访问权限设置**下，目录桶的所有屏蔽公共访问权限设置已自动启用。无法修改目录桶的这些设置。有关阻止公共访问的更多信息，请参阅[阻止对您的 Amazon S3 存储的公有访问](access-control-block-public-access.md)。

1. 默认情况下，在**默认加密**下，目录存储桶使用**具有 Amazon S3 托管式密钥的服务器端加密（SSE-S3）**来加密数据。还可以选择使用**具有 AWS Key Management Service 密钥的服务器端加密（SSE-KMS）**对目录存储桶中的数据进行加密。

1. 选择 **创建存储桶 **。

   创建存储桶后，您可以向存储桶中添加文件和文件夹。有关更多信息，请参阅 [使用目录桶中的对象](directory-buckets-objects.md)。

## 使用 AWS CLI
<a name="create-directory-bucket-lz-cli"></a>

此示例说明如何在本地区域中使用 AWS CLI 创建目录存储桶。要使用该命令，请将*用户输入占位符* 替换为您自己的信息。

创建目录存储桶时，必须提供配置详细信息并使用以下命名约定：`bucket-base-name--zone-id--x-s3`。

```
aws s3api create-bucket
--bucket bucket-base-name--zone-id--x-s3
--create-bucket-configuration 'Location={Type=LocalZone,Name=local-zone-id},Bucket={DataRedundancy=SingleLocalZone,Type=Directory}'
--region parent-region-code
```

有关本地区域 ID 和父区域代码的更多信息，请参阅[Local Zones 中目录存储桶的概念](s3-lzs-for-directory-buckets.md)。有关 AWS CLI 命令的更多信息，请参阅《AWS CLI Command Reference》**中的 [create-bucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/create-bucket.html)。

## 使用 AWS SDK
<a name="create-directory-bucket-lz-sdks"></a>

------
#### [ SDK for Go ]

此示例说明如何在本地区域中使用适用于 Go 的 AWS SDK 创建目录存储桶。

**Example**  

```
var bucket = "bucket-base-name--zone-id--x-s3" // The full directory bucket name

func runCreateBucket(c *s3.Client) {
    resp, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{
        Bucket: &bucket,
        CreateBucketConfiguration: &types.CreateBucketConfiguration{
            Location: &types.LocationInfo{
                Name: aws.String("local-zone-id"),
                Type: types.LocationTypeLocalZone,
            },  
            Bucket: &types.BucketInfo{
                DataRedundancy: types.DataRedundancySingleLocalZone,
                Type:           types.BucketTypeDirectory,
            },  
        },  
    })  
    var terr *types.BucketAlreadyOwnedByYou
    if errors.As(err, &terr) {
        fmt.Printf("BucketAlreadyOwnedByYou: %s\n", aws.ToString(terr.Message))
        fmt.Printf("noop...\n") // No operation performed, just printing a message
        return
    }   
    if err != nil {
        log.Fatal(err)
    }   

    fmt.Printf("bucket created at %s\n", aws.ToString(resp.Location))
}
```

------
#### [ SDK for Java 2.x ]

此示例说明如何在本地区域中使用AWS SDK for Java 2.x 创建目录存储桶。

**Example**  

```
public static void createBucket(S3Client s3Client, String bucketName) {

    //Bucket name format is {base-bucket-name}--{local-zone-id}--x-s3
    //example: doc-example-bucket--local-zone-id--x-s3 is a valid name for a directory bucket created in a Local Zone.

    CreateBucketConfiguration bucketConfiguration = CreateBucketConfiguration.builder()
             .location(LocationInfo.builder()
                     .type(LocationType.LOCAL_ZONE)
                     .name("local-zone-id").build()) //this must match the Local Zone ID in your bucket name
             .bucket(BucketInfo.builder()
                    .type(BucketType.DIRECTORY)
                    .dataRedundancy(DataRedundancy.SINGLE_LOCAL_ZONE)
                    .build()).build();
    try {
    
             CreateBucketRequest bucketRequest = CreateBucketRequest.builder().bucket(bucketName).createBucketConfiguration(bucketConfiguration).build();
             CreateBucketResponse response = s3Client.createBucket(bucketRequest);
             System.out.println(response);
    } 
    
    catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
         }
    }
```

------
#### [ 适用于 JavaScript 的 AWS SDK ]

此示例说明如何在本地区域中使用适用于 JavaScript 的 AWS SDK 创建目录存储桶。

**Example**  

```
// file.mjs, run with Node.js v16 or higher
// To use with the preview build, place this in a folder 
// inside the preview build directory, such as /aws-sdk-js-v3/workspace/

import { S3 } from "@aws-sdk/client-s3";

const region = "parent-region-code";
const zone = "local-zone-id";
const suffix = `${zone}--x-s3`;

const s3 = new S3({ region });

const bucketName = `bucket-base-name--${suffix}`; // Full directory bucket name

const createResponse = await s3.createBucket( 
    { Bucket: bucketName, 
      CreateBucketConfiguration: {Location: {Type: "LocalZone", Name: "local-zone-id"},
      Bucket: { Type: "Directory", DataRedundancy: "SingleLocalZone" }}
    } 
   );
```

------
#### [ 适用于 .NET 的 SDK ]

此示例说明如何在本地区域中使用适用于 .NET 的 SDK 创建目录存储桶。

**Example**  

```
using (var amazonS3Client = new AmazonS3Client())
{
    var putBucketResponse = await amazonS3Client.PutBucketAsync(new PutBucketRequest
    {

       BucketName = "bucket-base-name--local-zone-id--x-s3",
       PutBucketConfiguration = new PutBucketConfiguration
       {
         BucketInfo = new BucketInfo { DataRedundancy = DataRedundancy.SingleLocalZone, Type = BucketType.Directory },
         Location = new LocationInfo { Name = "local-zone-id", Type = LocationType.LocalZone }
       }
     }).ConfigureAwait(false);
}
```

------
#### [ SDK for PHP ]

此示例说明如何在本地区域中使用AWS SDK for PHP 创建目录存储桶。

**Example**  

```
require 'vendor/autoload.php';

$s3Client = new S3Client([

    'region'      => 'parent-region-code',
]);


$result = $s3Client->createBucket([
    'Bucket' => 'bucket-base-name--local-zone-id--x-s3',
    'CreateBucketConfiguration' => [
        'Location' => ['Name'=> 'local-zone-id', 'Type'=> 'LocalZone'],
        'Bucket' => ["DataRedundancy" => "SingleLocalZone" ,"Type" => "Directory"]   ],
]);
```

------
#### [ SDK for Python ]

此示例说明如何在本地区域中使用适用于 Python (Boto3) 的 AWS SDK 创建目录存储桶。

**Example**  

```
import logging
import boto3
from botocore.exceptions import ClientError

def create_bucket(s3_client, bucket_name, local_zone):
    '''
    Create a directory bucket in a specified Local Zone

    :param s3_client: boto3 S3 client
    :param bucket_name: Bucket to create; for example, 'bucket-base-name--local-zone-id--x-s3'
    :param local_zone: String; Local Zone ID to create the bucket in
    :return: True if bucket is created, else False
    '''

    try:
        bucket_config = {
                'Location': {
                    'Type': 'LocalZone',
                    'Name': local_zone
                },
                'Bucket': {
                    'Type': 'Directory', 
                    'DataRedundancy': 'SingleLocalZone'
                }
            }
        s3_client.create_bucket(
            Bucket = bucket_name,
            CreateBucketConfiguration = bucket_config
        )
    except ClientError as e:
        logging.error(e)
        return False
    return True


if __name__ == '__main__':
    bucket_name = 'BUCKET_NAME'
    region = 'parent-region-code'
    local_zone = 'local-zone-id'
    s3_client = boto3.client('s3', region_name = region)
    create_bucket(s3_client, bucket_name, local_zone)
```

------
#### [ SDK for Ruby ]

此示例说明如何在本地区域中使用适用于 Ruby 的 AWS SDK 创建目录存储桶。

**Example**  

```
s3 = Aws::S3::Client.new(region:'parent-region-code')
s3.create_bucket(
  bucket: "bucket-base-name--local-zone-id--x-s3",
  create_bucket_configuration: {
    location: { name: 'local-zone-id', type: 'LocalZone' },
    bucket: { data_redundancy: 'SingleLocalZone', type: 'Directory' }
  }
)
```

------