

# 开始使用标准分配（AWS CLI）
<a name="get-started-cli-tutorial"></a>

本节中的过程将介绍如何将 AWS CLI 与 CloudFront 使用来设置涉及以下操作的基本配置：
+ 创建 Amazon S3 存储桶以用作分配源。
+ 将对象的原始版本存储在 S3 存储桶中。
+ 使用来源访问控制（OAC）将经过身份验证的请求发送到 Amazon S3 源。OAC 通过 CloudFront 发送请求，以防止查看器直接访问您的 S3 存储桶。有关 OAC 的更多信息，请参阅[限制对 Amazon S3 源的访问](private-content-restricting-access-to-s3.md)。
+ 将 URL 中的 CloudFront 域名用于您的对象（例如 `https://d111111abcdef8.cloudfront.net/index.html`）。
+ 在 CloudFront 边缘站点中将对象保留默认的 24 小时持续时间（最短持续时间为 0 秒）

其中的大多数选项是可自定义的。有关如何自定义 CloudFront 分配选项的信息，请参阅[创建分配](distribution-web-creating-console.md)。

## 先决条件
<a name="get-started-cli-prereqs"></a>

开始之前，请确保您已完成[设置您的 AWS 账户](setting-up-cloudfront.md)中的步骤。

安装 AWS CLI 并使用您的凭证对其进行配置。有关更多信息，请参阅《AWS CLI 用户指南》**中的 [AWS CLI 入门](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。



## 创建 Amazon S3 存储桶
<a name="get-started-cli-create-bucket"></a>

Amazon S3 存储桶是文件（对象）或文件夹的容器。当 Amazon S3 存储桶作为源时，CloudFront 可以为您分发几乎任何类型的文件。例如，CloudFront 可以分配文本、图像和视频。您可以在 Amazon S3 上存储的数据量没有上限。

在本教程中，您将创建一个 S3 存储桶并上传一个 HTML 文件，该文件用于创建基本网页。

```
aws s3 mb s3://amzn-s3-demo-bucket/ --region us-east-1
```

将 *amzn-s3-demo-bucket* 替换为全局唯一的存储桶名称。对于 AWS 区域，建议选择地理位置靠近您的区域。这可以减少延迟和成本，但也可以选择其它区域。例如，您可以这样做来满足监管要求。

## 将内容上传到存储桶
<a name="get-started-cli-upload-content"></a>

在本教程中，下载并提取基本“Hello World”网页的示例内容文件。

```
# Create a temporary directory
mkdir -p ~/cloudfront-demo

# Download the sample Hello World files
curl -o ~/cloudfront-demo/hello-world-html.zip https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/samples/hello-world-html.zip

# Extract the zip file
unzip ~/cloudfront-demo/hello-world-html.zip -d ~/cloudfront-demo/hello-world
```

这将创建一个包含 `index.html` 文件和 `css` 文件夹的目录。将这些文件上传到 S3 存储桶。

```
aws s3 cp ~/cloudfront-demo/hello-world/ s3://amzn-s3-demo-bucket/ --recursive
```

## 创建来源访问控制（OAC）
<a name="get-started-cli-create-oac"></a>

在本教程中，您将创建来源访问控制（OAC）。OAC 可帮助您安全地将经过身份验证的请求发送到 Amazon S3 源。有关 OAC 的更多信息，请参阅[限制对 Amazon S3 源的访问](private-content-restricting-access-to-s3.md)。

```
aws cloudfront create-origin-access-control \
    --origin-access-control-config Name="oac-for-s3",SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3
```

将输出中的 OAC ID 保存为环境变量。将示例值替换为您自己的 OAC ID。您将在下一步中使用它。

```
OAC_ID="E1ABCD2EFGHIJ"
```

## 创建标准分配
<a name="get-started-cli-create-classic"></a>

创建一个名为 `distribution-config.json` 的分配配置文件。将示例存储桶名称替换为与 `Id`、`DomainName` 和 `TargetOriginId` 值对应的存储桶名称。

```
cat > distribution-config.json << EOF
{
    "CallerReference": "cli-example-$(date +%s)",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "S3-amzn-s3-demo-bucket",
                "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                },
                "OriginAccessControlId": "$OAC_ID"
            }
        ]
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "S3-amzn-s3-demo-bucket",
        "ViewerProtocolPolicy": "redirect-to-https",
        "AllowedMethods": {
            "Quantity": 2,
            "Items": ["GET", "HEAD"],
            "CachedMethods": {
                "Quantity": 2,
                "Items": ["GET", "HEAD"]
            }
        },
        "DefaultTTL": 86400,
        "MinTTL": 0,
        "MaxTTL": 31536000,
        "Compress": true,
        "ForwardedValues": {
            "QueryString": false,
            "Cookies": {
                "Forward": "none"
            }
        }
    },
    "Comment": "CloudFront distribution for S3 bucket",
    "Enabled": true
}
EOF
```

创建标准分配。

```
aws cloudfront create-distribution --distribution-config file://distribution-config.json
```

将输出中的分配 ID 和域名保存为环境变量。将 example values 替换为您自己的值。本教程后面将会用到这些值。

```
DISTRIBUTION_ID="EABCD1234XMPL"
DOMAIN_NAME="d111111abcdef8.cloudfront.net"
```

在生产环境中使用本教程中的分配和 S3 存储桶之前，请务必对其进行配置以满足您的特定需求。有关在生产环境中配置访问权限的信息，请参阅[配置安全访问和限制对内容的访问](SecurityAndPrivateContent.md)。

## 更新 S3 存储桶策略
<a name="get-started-cli-update-bucket-policy"></a>

更新 S3 存储桶策略以支持 CloudFront 访问对象。将示例存储桶名称替换为您的存储桶名称。

```
# Get your AWS account ID
ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text)

# Create the bucket policy
cat > bucket-policy.json << EOF
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipal",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceArn": "arn:aws:cloudfront::$ACCOUNT_ID:distribution/$DISTRIBUTION_ID"
                }
            }
        }
    ]
}
EOF

# Apply the bucket policy
aws s3api put-bucket-policy \
    --bucket amzn-s3-demo-bucket \
    --policy file://bucket-policy.json
```

## 确认分配部署
<a name="get-started-cli-confirm-deployment"></a>

创建分配后，需要一些时间才能完成部署。当分配状态从 `InProgress` 变为 `Deployed` 时，继续执行下一步。

```
aws cloudfront get-distribution --id $DISTRIBUTION_ID --query 'Distribution.Status'
```

或者，您可以使用 `wait` 命令等待分配部署。

```
aws cloudfront wait distribution-deployed --id $DISTRIBUTION_ID
```

## 通过 CloudFront 访问您的内容
<a name="get-started-cli-access-content"></a>

要通过 CloudFront 访问您的内容，请将 CloudFront 分配的域名与内容的主页组合在一起。将示例 CloudFront 域名替换为您自己的域名。

```
https://d111111abcdef8.cloudfront.net/index.html
```

如果您按照上述步骤操作并创建了 HTML 文件，您应该看到显示 **Hello world\$1** 的网页。

将更多内容上传到此 S3 桶时，您可以将 CloudFront 分配域名与 S3 桶中的对象路径组合在一起，从而通过 CloudFront 访问内容。例如，如果您将一个名为 `new-page.html` 的新文件上传到 S3 桶的根目录，URL 如下所示：

`https://d111111abcdef8.cloudfront.net/new-page.html`.

## 清理
<a name="get-started-cli-cleanup"></a>

如果您仅出于练习目的创建分配和 S3 存储桶，请删除它们，这样就不会再产生费用。首先禁用和删除分配。

**禁用和删除标准分配（AWS CLI）**

1. 首先，禁用分配。

   ```
   # Get the current configuration and ETag
   ETAG=$(aws cloudfront get-distribution-config --id $DISTRIBUTION_ID --query 'ETag' --output text)
   
   # Create a modified configuration with Enabled=false
   aws cloudfront get-distribution-config --id $DISTRIBUTION_ID | \
   jq '.DistributionConfig.Enabled = false' > temp_disabled_config.json
   
   # Update the distribution to disable it
   aws cloudfront update-distribution \
       --id $DISTRIBUTION_ID \
       --distribution-config file://<(jq '.DistributionConfig' temp_disabled_config.json) \
       --if-match $ETAG
   ```

1. 等待分配被禁用。

   ```
   aws cloudfront wait distribution-deployed --id $DISTRIBUTION_ID
   ```

1. 删除分配

   ```
   # Get the current ETag
   ETAG=$(aws cloudfront get-distribution-config --id $DISTRIBUTION_ID --query 'ETag' --output text)
   
   # Delete the distribution
   aws cloudfront delete-distribution --id $DISTRIBUTION_ID --if-match $ETAG
   ```

**删除 S3 存储桶（AWS CLI）**
+ 删除 S3 存储桶及其内容。将示例存储桶名称替换为您自己的存储桶名称。

  ```
  # Delete the bucket contents
  aws s3 rm s3://amzn-s3-demo-bucket --recursive
  
  # Delete the bucket
  aws s3 rb s3://amzn-s3-demo-bucket
  ```

要清理为本教程创建的本地文件，请运行以下命令：

```
# Clean up local files
rm -f distribution-config.json bucket-policy.json temp_disabled_config.json
rm -rf ~/cloudfront-demo
```

（可选）您可以删除为本教程创建的 OAC。

```
# Get the OAC ETag
OAC_ETAG=$(aws cloudfront get-origin-access-control --id $OAC_ID --query 'ETag' --output text)

# Delete the OAC
aws cloudfront delete-origin-access-control --id $OAC_ID --if-match $OAC_ETAG
```