Ilg*_*iev 4 amazon-web-services aws-cdk
我正在尝试将 vpc cidr 作为输入参数传递,如下所示:
import { Stack, StackProps, Construct, CfnParameter } from '@aws-cdk/core';
import { Vpc, SubnetType } from '@aws-cdk/aws-ec2';
export class VpcStructureCdkStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// VPC CIDR as input parameter
const vpcCidr = new CfnParameter(this, 'vpcCidr', {
type: 'String',
description: 'Please enter the IP range (CIDR notation) for this VPC',
allowedPattern: '((\d{1,3})\.){3}\d{1,3}/\d{1,2}'
})
// The code that defines your stack goes here
new Vpc(this, 'VPC', {
maxAzs: 3,
cidr: vpcCidr.valueAsString,
subnetConfiguration: [
{
name: 'App',
subnetType: SubnetType.PRIVATE,
cidrMask: 24
},
...
Run Code Online (Sandbox Code Playgroud)
但出现以下错误:
Error: 'cidr' property must be a concrete CIDR string, got a Token (we need to parse it for automatic subdivision)
Run Code Online (Sandbox Code Playgroud)
使用环境变量时出现同样的错误。
有什么方法可以不硬编码 vpc cidr 吗?
来自CDK 参数的文档:
CfnParameter 实例通过令牌向您的 AWS CDK 应用程序公开其值。与所有令牌一样,参数的令牌在综合时解析,但它解析为对 AWS CloudFormation 模板中定义的参数的引用,该引用将在部署时解析,而不是解析为具体值。[...] 一般来说,我们建议不要将 AWS CloudFormation 参数与 AWS CDK 一起使用。
尤其是最后一句话至关重要。
现在怎么解决呢?
好吧,正如您已经说过的:通过编程语言使用环境变量。我不知道你对环境变量的处理方法,因为你没有展示它。让我举一个例子。
// file: lib/your_stack.ts
export class VpcStructureCdkStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// reading the value from the env.
// Obviously, you have to set it before or pass it before you call any cdk command
const vpcCidr = process.env.VPC_CIDR;
new Vpc(this, 'VPC', {
maxAzs: 3,
// passing it
cidr: vpcCidr,
subnetConfiguration: [
{
name: 'App',
subnetType: SubnetType.PRIVATE,
cidrMask: 24
},
// ...
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这只是将可配置值输入 CDK 的一种方法。
更好且可调试的方法是在Context中设置所有动态/用户/域值。实现自己价值观的最佳场所是在内部cdk.json。如果它还不存在,只需创建它,并且不要忘记将其放入 Git(或您选择的 VCS)中。
{
// ...
context: {
// ...
"VpcCidr": "10.0.0.0/8",
}
}
Run Code Online (Sandbox Code Playgroud)
如果该cdk.json方法还不够,您还有另一种选择:
通过将其cdk synth/deploy作为参数传递给-c/--context vpcCidr=10.0.0.0/8. 然而,这更难调试,因为它不一定是版本化的。
在您的堆栈中(恕我直言,这是执行此操作的最佳位置),您可以调用以下方法从上下文中检索实际值:
const vpcCidr = this.node.tryGetContext("VpcCidr");
Run Code Online (Sandbox Code Playgroud)
并将其传递给您的 VPC 构造函数。
| 归档时间: |
|
| 查看次数: |
3244 次 |
| 最近记录: |