

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

# 將大量 DNS 記錄遷移至 Amazon Route 53 私有託管區域
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone"></a>

*Ram Kandaswamy，Amazon Web Services*

## 總結
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-summary"></a>

網路工程師和雲端管理員需要有效率且簡單的方法，將網域名稱系統 (DNS) 記錄新增至 Amazon Route 53 中的私有託管區域。使用手動方法將項目從 Microsoft Excel 工作表複製到 Route 53 主控台中的適當位置很繁瑣且容易出錯。此模式描述自動化方法，可減少新增多個記錄所需的時間和精力。它也為多個託管區域建立提供一組可重複的步驟。

此模式使用 Amazon Simple Storage Service (Amazon S3) 來存放記錄。為了有效率地使用資料，模式使用 JSON 格式，因為它簡單且能夠支援 Python 字典 (`dict` 資料類型）。

**注意**  
如果您可以從系統產生區域檔案，請考慮改用 [Route 53 匯入功能](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating-import.html)。

## 先決條件和限制
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-prereqs"></a>

**先決條件**
+ 包含私有託管區域記錄的 Excel 工作表
+ 熟悉不同類型的 DNS 記錄，例如 A 記錄、Name Authority Pointer (NAPTR) 記錄和 SRV 記錄 （請參閱[支援的 DNS 記錄類型](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html))
+ 熟悉 Python 語言及其程式庫

**限制**
+ 模式不會為所有使用案例案例提供廣泛的涵蓋範圍。例如，[Change\$1resource\$1record\$1sets](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets) 呼叫不會使用 API 的所有可用屬性。
+ 在 Excel 工作表中，假設每一列中的值是唯一的。每個完整網域名稱 (FQDN) 的多個值預期會出現在相同的資料列中。如果不正確，您應該修改此模式中提供的程式碼，以執行必要的串連。
+ 模式使用適用於 Python 的 AWS 開發套件 (Boto3) 直接呼叫 Route 53 服務。您可以增強程式碼以使用 `create_stack`和 `update_stack`命令的 AWS CloudFormation 包裝函式，並使用 JSON 值填入範本資源。

## Architecture
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-architecture"></a>

**技術堆疊**
+ 用於路由流量的 Route 53 私有託管區域
+ 用於儲存輸出 JSON 檔案的 Amazon S3 

![\[將大量 DNS 記錄遷移至 Route 53 私有託管區域的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/a81c29ea-f0c5-4d4a-ba87-93111a0f1ee9/images/2ada844b-4147-4f9f-8883-d22605aa42d8.png)


工作流程包含這些步驟，如上圖所示，並在 *Epics* 章節中討論：

1. 將具有記錄集資訊的 Excel 工作表上傳至 S3 儲存貯體。

1. 建立並執行 Python 指令碼，將 Excel 資料轉換為 JSON 格式。

1. 從 S3 儲存貯體讀取記錄並清除資料。

1. 在私有託管區域中建立記錄集。

## 工具
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-tools"></a>
+ [Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) –Amazon Route 53 是高度可用且可擴展的 DNS Web 服務，可處理網域註冊、DNS 路由和運作狀態檢查。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一種物件儲存服務。您可以使用 Amazon S3 隨時從 Web 任何地方存放和擷取任意資料量。

## 史詩
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-epics"></a>

### 準備資料以進行自動化
<a name="prepare-data-for-automation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為您的記錄建立 Excel 檔案。 | 使用您從目前系統匯出的記錄來建立 Excel 工作表，其中包含記錄的必要資料欄，例如完整網域名稱 (FQDN)、記錄類型、存留時間 (TTL) 和值。對於 NAPTR 和 SRV 記錄，值是多個屬性的組合，因此請使用 Excel 的 `concat`方法來合併這些屬性。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.html) | 資料工程師、Excel 技能 | 
| 驗證工作環境。 | 在您的 IDE 中，建立 Python 檔案，將 Excel 輸入工作表轉換為 JSON 格式。（您也可以使用 Amazon SageMaker 筆記本來使用 Python 程式碼，而不是 IDE。)確認您使用的 Python 版本是 3.7 版或更新版本。<pre> python3 --version</pre>安裝 **pandas** 套件。<pre> pip3 install pandas --user</pre> | 一般 AWS | 
| 將 Excel 工作表資料轉換為 JSON。 | 建立 Python 檔案，其中包含要從 Excel 轉換為 JSON 的下列程式碼。<pre>import pandas as pd<br />data=pd.read_excel('./Book1.xls')<br />data.to_json(path_or_buf='my.json',orient='records')</pre>其中 `Book1`是 Excel 工作表的名稱，而 `my.json`是輸出 JSON 檔案的名稱。 | 資料工程師、Python 技能 | 
| 將 JSON 檔案上傳至 S3 儲存貯體。 | 上傳 `my.json` 至 S3 儲存貯體。如需詳細資訊，請參閱 Amazon S3 文件中的[建立儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體。 | 應用程式開發人員 | 
| FqdnName | RecordType | Value | TTL | 
| something.example.org | A | 1.1.1.1 | 900 | 

### 插入記錄
<a name="insert-records"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立私有託管區域。 | 使用 [create\$1hosted\$1zone](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.create_hosted_zone) API 和下列 Python 範例程式碼來建立私有託管區域。將參數 `hostedZoneName`、 `vpcRegion`和 取代`vpcId`為您自己的值。<pre>import boto3<br />import random<br />hostedZoneName ="xxx"<br />vpcRegion = "us-east-1"<br />vpcId="vpc-xxxx"<br />route53_client = boto3.client('route53')<br />response = route53_client.create_hosted_zone(<br />        Name= hostedZoneName,<br />        VPC={<br />            'VPCRegion: vpcRegion,<br />            'VPCId': vpcId<br />        },<br />        CallerReference=str(random.random()*100000),<br />        HostedZoneConfig={<br />            'Comment': "private hosted zone created by automation",<br />            'PrivateZone': True<br />        }<br />    )<br /> print(response)</pre>您也可以使用基礎設施即程式碼 (IaC) 工具，例如 AWS CloudFormation，將這些步驟取代為使用適當資源和屬性建立堆疊的範本。 | 雲端架構師、網路管理員、Python 技能 | 
| 從 Amazon S3 擷取做為字典的詳細資訊。 | 使用下列程式碼從 S3 儲存貯體讀取，並以 Python 字典的形式取得 JSON 值。 <pre>fileobj = s3_client.get_object(<br />        Bucket=bucket_name,<br />        Key='my.json'<br />        )<br />    filedata = fileobj['Body'].read()<br />    contents = filedata.decode('utf-8')<br />    json_content=json.loads(contents)<br />    print(json_content)</pre>其中 `json_content`包含 Python 字典。 | 應用程式開發人員、Python 技能 | 
| 清除空格和 Unicode 字元的資料值。 | 為了確保資料正確性的安全措施，請使用下列程式碼對 中的值執行條紋操作`json_content`。此程式碼會移除每個字串前面和結尾的空格字元。它也會使用 `replace`方法來移除硬 （不中斷） 空格 (`\xa0`字元）。<pre>for item in json_content:<br />    fqn_name = unicodedata.normalize("NFKD",item["FqdnName"].replace("u'", "'").replace('\xa0', '').strip())<br />    rec_type = item["RecordType"].replace('\xa0', '').strip()<br />    res_rec = {<br />                 'Value': item["Value"].replace('\xa0', '').strip()<br />                }</pre> | 應用程式開發人員、Python 技能 | 
| 插入記錄。 | 使用以下程式碼做為上一個`for`迴圈的一部分。<pre>change_response = route53_client.change_resource_record_sets(<br />            HostedZoneId="xxxxxxxx",<br />            ChangeBatch={<br />                'Comment': 'Created by automation',<br />                'Changes': [<br />                    {<br />                        'Action': 'UPSERT',<br />                        'ResourceRecordSet': {<br />                            'Name': fqn_name,<br />                            'Type': rec_type,<br />                            'TTL': item["TTL"],<br />                            'ResourceRecords': res_rec<br />                        }<br />                    }<br />                ]<br />            }<br />    )</pre>其中 `xxxxxxx`是此史詩中第一個步驟的託管區域 ID。 | 應用程式開發人員、Python 技能 | 

## 相關資源
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-resources"></a>

**參考**
+ [透過匯入區域檔案建立記錄 ](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating-import.html)(Amazon Route 53 文件）
+ [create\$1hosted\$1zone 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.create_hosted_zone) (Boto3 文件）
+ [change\$1resource\$1record\$1sets 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets) (Boto3 文件）

**教學課程和影片**
+ [Python 教學課程](https://docs.python.org/3/tutorial/) (Python 文件）
+ [使用 Amazon Route 53 的 DNS 設計](https://www.youtube.com/watch?v=2y_RBjDkRgY) (YouTube 影片、*AWS Online Tech Talks*)