AWS-CDK:有什么方法可以通过输入参数传递vpc cidr?

2023-12-05

我正在尝试将 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
        },
...

但出现以下错误:

Error: 'cidr' property must be a concrete CIDR string, got a Token (we need to parse it for automatic subdivision)

使用环境变量时出现同样的错误。

有什么方法可以不硬编码 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
        },
        // ...
      ]
    }
   }
}

但这只是将可配置值输入 CDK 的一种方法。

更好且可调试的方法是在中设置所有动态/用户/域值Context。 实现自己价值观的最佳场所是在cdk.json。如果它还不存在,只需创建它,并且不要忘记将其放入 Git(或您选择的 VCS)中。

{
  // ...
  context: {
    // ...
    "VpcCidr": "10.0.0.0/8",
  }
}

If the cdk.json方法还不够,您还有另一种选择:

传递给cdk synth/deploy作为论证通过-c/--context vpcCidr=10.0.0.0/8。 然而,这更难调试,因为它不一定是版本化的。

在您的堆栈中(恕我直言,这是执行此操作的最佳位置),您可以调用以下方法从上下文中检索实际值:

const vpcCidr = this.node.tryGetContext("VpcCidr");

并将其传递给您的 VPC 构造函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AWS-CDK:有什么方法可以通过输入参数传递vpc cidr? 的相关文章

随机推荐