如何用AWS CDK设置Route53 PublicHostedZone的NS记录TTL?
问题描述
我通过以下代码创建了一个Route 53区域:
this.apiV2Zone = new PublicHostedZone(this, "ApiV2", { zoneName: "api-v2.example.com" });
区域已按预期创建,但我发现NS记录的TTL属性被设置为172800(2天)。由于目前仅处于测试阶段,这个值偏高,暂时设置更低的TTL不会产生过多成本。
那么,如何通过CDK设置NS记录的TTL呢?
已尝试方案
我尝试自行强制创建NS记录,代码如下:
let target = RecordTarget.fromValues( ...this.apiV2Zone.hostedZoneNameServers ?? [] ); const recordSet = new RecordSet(this, 'ApiV2Ns', { recordType: RecordType.NS, target, zone: this.apiV2Zone, deleteExisting: true, recordName: this.apiV2Zone.zoneName, ttl: cdk.Duration.minutes(10), });
但部署失败,报错信息为:
Received response status [FAILED] from custom resource. Message returned: InvalidChangeBatch : [A HostedZone must contain at least one NS record for the zone itself.]
将deleteExisting设为false时同样失败,原因是重复创建了已存在的NS记录。
临时解决方法
在AWS控制台手动修改NS记录的TTL,执行CDK diff时未检测到变更。
解决方案
AWS CDK的高层PublicHostedZone构造函数未提供修改默认NS记录TTL的直接参数,因为这些NS记录由Route53自动管理。要设置自定义TTL,可改用底层的CfnHostedZone创建托管区域,通过hostedZoneConfig.zoneTtl指定TTL值(单位为秒):
import * as route53 from 'aws-cdk-lib/aws-route53'; const apiV2Zone = new route53.CfnHostedZone(this, 'ApiV2', { name: 'api-v2.example.com', hostedZoneConfig: { zoneTtl: '600' // 对应10分钟,需传入字符串格式的秒数 } });
说明
- 使用
CfnHostedZone创建的托管区域,其默认NS记录的TTL会自动设置为zoneTtl指定的值,无需手动创建或修改NS记录,避免了之前的部署错误。 - 若已通过
PublicHostedZone创建了区域,替换为CfnHostedZone时,可通过apiV2Zone.attrNameServers获取名称服务器列表,确保父域的NS配置不受影响。
内容的提问来源于stack exchange,提问作者Shorn
相关产品推荐
相关产品推荐

