AWS CDKでVPCを作成してみる

AWS CDKを使ってAWSのリソースを新規に作成してみます。

すでに以下がインストール済みのコンテナ内で作業します。

まずはVPCを作成する方法をChatGPTに質問してみました。

入力

How can I deploy AWS VPC by using AWS CDK in TypeScript?

出力

To deploy an AWS VPC using AWS CDK in TypeScript, you can follow these steps:

Install the AWS CDK and its dependencies by running the following command in your terminal:

npm install -g aws-cdk

Create a new directory for your AWS CDK project and navigate into it.

Initialize a new AWS CDK project by running the following command:

cdk init --language=typescript

Create a new file called vpc-stack.ts in the lib directory. This file will contain the code for your VPC stack.

Add the following code to the vpc-stack.ts file:

import * as cdk from 'aws-cdk-lib';
import { Stack, StackProps } from 'aws-cdk-lib';

import { Vpc, SubnetType } from 'aws-cdk-lib/aws-ec2';

export class VpcStack extends Stack {
  constructor(scope: cdk.Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const vpc = new Vpc(this, 'MyVpc', {
      cidr: '10.0.0.0/16',
      maxAzs: 2,
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Public',
          subnetType: SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Private',
          subnetType: SubnetType.PRIVATE,
        },
        {
          cidrMask: 28,
          name: 'Isolated',
          subnetType: SubnetType.ISOLATED,
        },
      ],
    });
  }
}

This code creates a new VPC with three types of subnets: public, private, and isolated.

In the bin directory, create a new file called deploy.ts with the following code:

import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { VpcStack } from '../lib/vpc-stack';

const app = new cdk.App();
new VpcStack(app, 'MyVpcStack');

This code creates a new CDK app and deploys the VpcStack you created in step 5.

Deploy your VPC stack by running the following command in your terminal:

Copy code cdk deploy This command will deploy your VPC stack to your AWS account.

Congratulations, you have now deployed an AWS VPC using AWS CDK in TypeScript!

手順1と2はすでに実行済みでしたのでスキップします。

手順3のAWS CDKプロジェクトを作成するコマンドを実行してみます。

cdk init --language=typescript

上記コマンドを実行すると、以下のようにファイルが生成されました。 (-Iオプションでnode_modulesディレクトリを除外しています)

tree -I 'node_modules'
.
├── bin
│   └── cdk20230420.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── cdk20230420-stack.ts
├── package.json
├── package-lock.json
├── README.md
├── test
│   └── cdk20230420.test.ts
└── tsconfig.json

3 directories, 9 files

手順4のvp-stack.tsファイルを作成します。

touch lib/vpc-stack.ts

手順5のChatGPTが出したコードではsubnetTypeを指定している部分でPRIVATEとなっていますが、手元ではPRIVATEというプロパティは存在せずPRIVATE_WITH_EGRESSなどがありましたので修正しました。

このあたりの設定は別の機会に深掘りしていこうと思います。

また、constructorの第一引数で渡しているcdk.Constructも存在しないためエラーになっていたので、ChatGPTに再度質問しました。

入力

With the code you suggested in vpc-stack.ts, I got below error. Could you fix it? Namespace '"/workspaces/cdk20230420/node_modules/aws-cdk-lib/index"' has no exported member 'Construct'.ts(2694)

出力

I apologize for the error in my previous response.

To fix the error you received, you need to import the Construct class from the @aws-cdk/core package instead of the aws-cdk-lib package.

Here's the updated code for vpc-stack.ts:

import * as cdk from 'aws-cdk-lib';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Vpc, SubnetType } from 'aws-cdk-lib/aws-ec2';

export class VpcStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const vpc = new Vpc(this, 'MyVpc', {
      cidr: '10.0.0.0/16',
      maxAzs: 2,
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Public',
          subnetType: SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Private',
          subnetType: SubnetType.PRIVATE,
        },
        {
          cidrMask: 28,
          name: 'Isolated',
          subnetType: SubnetType.ISOLATED,
        },
      ],
    });
  }
}

Make sure to save the changes to the file and then try running the cdk deploy command again.

Constructの部分は上記のコードでエラーは消えたのでそのまま進めてみます。 手元ではvpc-stack.tsのコードは以下のようになりました。

import * as cdk from 'aws-cdk-lib';
import {Stack, StackProps} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import {Vpc, SubnetType} from 'aws-cdk-lib/aws-ec2';

export class VpcStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        const vpc = new Vpc(this, 'VPC', {
        cidr: '10.0.0.0/16',
        maxAzs: 2,
        subnetConfiguration: [
            {
            cidrMask: 24,
            name: 'Public',
            subnetType: SubnetType.PUBLIC,
            },
            {
            cidrMask: 24,
            name: 'Private',
            subnetType: SubnetType.PRIVATE_WITH_EGRESS,
            },
            {
            cidrMask: 28,
            name: 'Isolated',
            subnetType: SubnetType.PRIVATE_ISOLATED,
            },
        ],
        });
    }
}

手順6のdeploy.tsファイルを作成します。

touch bin/deploy.ts

コードはChatGPTのコードをそのままコピーしました。

import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { VpcStack } from '../lib/vpc-stack';

const app = new cdk.App();
new VpcStack(app, 'MyVpcStack');

この状態で手順7のデプロイを実行します。

cdk deploy

しかし何もリソースが作成されませんでした。

cdk initを実行した時に作成されたbin/cdk20230420.tsにbin/deploy.tsと同じコードを書いて再度デプロイしてみました。

cdk deploy

するとVPCとサブネットが作成できていました。

まだまだ細かい仕様がわかってないので引き続き調査したいと思いますが、ひとまずCDKでAWSリソースが作成できました。