

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 開始使用標準分佈 (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 儲存貯體是檔案 (物件) 或資料夾的容器。CloudFront 使用 S3 儲存貯體做為來源時，能夠自動分佈幾乎任何類型的檔案。例如，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 和網域名稱儲存為環境變數。使用自己的取代範例值。您將在本教學課程稍後使用這些值。

```
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
```