TL;DR 名称的实际值在部署时解析。在合成时,您可以将loadBalancerDnsName 传递给其他构造,CDK 将创建必要的引用。
诸如 DNS 地址之类的资源标识符通常仅在部署时才知道。 CDK 使用Tokens 来“表示只能在应用生命周期中稍后解析的值”。 ApplicationLoadBalancer 的 loadBalancerDnsName: string 属性是其值解析为字符串 Token 占位符的属性之一
在合成时和部署时的实际值。
这是在构造之间传递loadBalancerDnsName 的示例:
export class AlbStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: cdk.StackProps) {
super(scope, id, props);
const alb = new elb.ApplicationLoadBalancer(this, 'MyALB', {
vpc: ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true }),
});
// WON'T WORK: at synth-time, the name attribute returns a Token, not the expected DNS name
console.log(alb.loadBalancerDnsName); // ${Token[TOKEN.220]}
// WILL WORK - CDK will wire up the token in CloudFormation as
new ssm.StringParameter(this, 'MyAlbDns', {
stringValue: alb.loadBalancerDnsName,
});
}
}
CDK 的 CloudFormation 模板输出具有 Fn::GetAtt 占位符,用于在部署时解析的 DNS 名称:
// CDK CloudFormation stack template
// Resources section
"MyAlbDnsFD44EB27": {
"Type": "AWS::SSM::Parameter",
"Properties": {
"Type": "String",
"Value": { "Fn::GetAtt": [ "MyALB911A8556", "DNSName" ] } // this will resolve to the string at deploy
},
"Metadata": {
"aws:cdk:path": "TsCdkPlaygroundAlbStack/MyAlbDns/Resource"
}
},