在 CDK 中创建后如何获取 ALB 的 URL?
Posted
技术标签:
【中文标题】在 CDK 中创建后如何获取 ALB 的 URL?【英文标题】:How to get the URL of the ALB after creating in CDK? 【发布时间】:2022-01-22 15:29:49 【问题描述】:我正在使用 AWS CDK v2 创建一个应用程序负载均衡器。
这是我的代码:
const lb = new elb.ApplicationLoadBalancer(this, 'LB',
vpc: ec2.Vpc.fromLookup(this, 'vpc-lookup',
isDefault: true
),
internetFacing: true
);
const listener = lb.addListener('Listener',
port: 80,
);
我的问题是如何获取负载均衡器的 URL(DNS 名称)?更新后我需要它在 CDK 中
【问题讨论】:
【参考方案1】: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"
,
【讨论】:
以上是关于在 CDK 中创建后如何获取 ALB 的 URL?的主要内容,如果未能解决你的问题,请参考以下文章
NSMutableArray 在 init 中创建后为空(带代码)
在 purescript-halogen 中创建后自动聚焦输入元素