首页 > 解决方案 > AWS-CDK:有什么方法可以通过输入参数传递 vpc cidr?

问题描述

我正在尝试将 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?

标签: amazon-web-servicesaws-cdk

解决方案


CDK 参数的文档:

CfnParameter 实例通过 token向您的 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",
  }
}

如果该cdk.json方法还不够,您还有另一种选择:

通过 将其cdk synth/deploy作为参数传递给-c/--context vpcCidr=10.0.0.0/8. 但是,这更难调试,因为它不一定是版本化的。

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

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

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


推荐阅读