

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 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*

## Summary
<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 记录、域名授权指针 (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 的 Amazon SDK (Boto3) 直接调用 Route 53 服务。您可以增强代码以使用`create_stack`和`update_stack`命令的 AWS CloudFormation 封装器，并使用 JSON 值填充模板资源。

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

**技术堆栈**
+ Route 53 私有托管区，用于路由流量
+ Amazon S3，用于存储输出 JSON 文件 

![\[将 DNS 记录批量迁移至 Amazon Route 53 私有托管区的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a81c29ea-f0c5-4d4a-ba87-93111a0f1ee9/images/2ada844b-4147-4f9f-8883-d22605aa42d8.png)


工作流由以下步骤组成，如上图所示，并在*操作说明*部分中进行了讨论：

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 网络服务，用于处理域注册、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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Excel 文件作为记录。 | 使用从当前系统导出的记录创建一个 Excel 工作表，其中包含记录所需列，例如完全限定域名 (FQDN)、记录类型、生存时间 (TTL) 和值。对于 NAPTR 和 SRV 记录，该值是多个属性的组合，因此请使用 Excel `concat` 方法来组合这些属性。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.html) | 数据工程师、Excel 技能 | 
| 验证工作环境。 | 在 IDE 中，创建一个 Python 文件以将 Excel 输入工作表转换为 JSON 格式。（你也可以使用亚马逊 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 | 值 | TTL | 
| something.example.org | A | 1.1.1.1 | 900 | 

### 插入记录
<a name="insert-records"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建私有托管区 | 使用 [create\$1hosted\$1zone API](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.create_hosted_zone) 及以下 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>您也可以使用诸如 AWS 之类的基础设施即代码 (IaC) 工具， 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 进行域名系统设计](https://www.youtube.com/watch?v=2y_RBjDkRgY)（YouTube 视频，*AWS 在线技术讲座*）