当您在同一区域内运行多个 CloudFormation 堆栈时,您可以使用 CloudFormation Outputs 跨堆栈共享引用。
但是,正如该文档强调的那样,输出不能用于跨区域引用。
You can't create cross-stack references across regions. You can use the intrinsic function Fn::ImportValue to import only values that have been exported within the same region.
如何在 CloudFormation 中跨区域引用值?
举个例子,我有一个 Route 53 hosted zone部署在 us-east-1
。但是,我在 us-west-2
中有一个后端,我想创建一个 DNS-validated ACM certificate这需要对托管区域的引用,以便能够创建适当的 CNAME 来证明所有权。
我如何从 us-west-2
中引用在 us-east-1
中创建的托管区域 ID?
最佳答案
我发现执行此操作的最简单方法是将您想要共享的引用(即本例中的托管区域 ID)写入 Systems Manager Parameter Store然后使用 custom resource 在单独区域的“子”堆栈中引用该值.
幸运的是,如果您的模板是使用 Cloud Development Kit (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 });
关于amazon-web-services - CloudFormation 跨区域引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59774627/