我发现执行此操作的最简单方法是将要共享的引用(即本例中的托管区域 ID)写入Systems Manager Parameter Store,然后使用单独区域的“子”堆栈中引用该值自定义资源。
幸运的是,如果您的模板是使用云开发工具包 (CDK)创建的,这将非常容易。
对于要从 SSM 读取的自定义资源,您可以使用如下内容:
// ssm-parameter-reader.ts
import { Construct } from '@aws-cdk/core';
import { AwsCustomResource, AwsSdkCall } from '@aws-cdk/custom-resources';
interface SSMParameterReaderProps {
parameterName: string;
region: string;
}
export class SSMParameterReader extends AwsCustomResource {
constructor(scope: Construct, name: string, props: SSMParameterReaderProps) {
const { parameterName, region } = props;
const ssmAwsSdkCall: AwsSdkCall = {
service: 'SSM',
action: 'getParameter',
parameters: {
Name: parameterName
},
region,
physicalResourceId: Date.now().toString() // Update physical id to always fetch the latest version
};
super(scope, name, { onUpdate: ssmAwsSdkCall });
}
public getParameterValue(): string {
return this.getData('Parameter.Value').toString();
}
}
要将托管区域 ID 写入参数存储,您只需执行以下操作:
// route53.ts (deployed in us-east-1)
import { PublicHostedZone } from '@aws-cdk/aws-route53';
import { StringParameter } from '@aws-cdk/aws-ssm';
export const ROUTE_53_HOSTED_ZONE_ID_SSM_PARAM = 'ROUTE_53_HOSTED_ZONE_ID_SSM_PARAM';
/**
* Other Logic
*/
const hostedZone = new PublicHostedZone(this, 'WebsiteHostedZone', { zoneName: 'example.com' });
new StringParameter(this, 'Route53HostedZoneIdSSMParam', {
parameterName: ROUTE_53_HOSTED_ZONE_ID_SSM_PARAM,
description: 'The Route 53 hosted zone id for this account',
stringValue: hostedZone.hostedZoneId
});
最后,您可以使用我们刚刚创建的自定义资源从该区域的参数存储中读取该值,并使用它在us-west-2
.
// acm.ts (deployed in us-west-2)
import { DnsValidatedCertificate } from '@aws-cdk/aws-certificatemanager';
import { PublicHostedZone } from '@aws-cdk/aws-route53';
import { ROUTE_53_HOSTED_ZONE_ID_SSM_PARAM } from './route53';
import { SSMParameterReader } from './ssm-parameter-reader';
/**
* Other Logic
*/
const hostedZoneIdReader = new SSMParameterReader(this, 'Route53HostedZoneIdReader', {
parameterName: ROUTE_53_HOSTED_ZONE_ID_SSM_PARAM,
region: 'us-east-1'
});
const hostedZoneId: string = hostedZoneIdReader.getParameterValue();
const hostedZone = PublicHostedZone.fromPublicHostedZoneId(this, 'Route53HostedZone', hostedZoneId);
const certificate = new DnsValidatedCertificate(this, 'ApiGatewayCertificate', { 'pdx.example.com', hostedZone });