AWSAWS CDK

Create CloudFormation Template using AWS CDK (TypeScript)

AWS CDK is a great tool to define our AWS Infrastructure by code. If we using TypeScript, we can get type supp […]

広告ここから
広告ここまで

AWS CDK is a great tool to define our AWS Infrastructure by code. If we using TypeScript, we can get type support to define and understand AWS services.

Why export CloudFormation?

AWS CDK can deploy CloudFormation by itself. But, sometimes we need to get the CloudFormation stack templates.

  • Provide the template to AWS MarketPlace
  • Upload the template to AWS ServiceCatalog
  • Use the template into ASK CLI(v2)
  • etc…

How can we export to CloudFormation template?

AWS CDK has a cool utility! To use the SynthUtils.toCloudFormation method, we can easy to convert your CDK stack to CloudFormation JSON.

import { Stack, Construct, StackProps, Fn, CfnMapping, App } from "@aws-cdk/core";
import { SynthUtils } from '@aws-cdk/assert'
import { CfnInstance } from "@aws-cdk/aws-ec2";

// Example stack
class DevStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props)
        new CfnMapping(
            this,
            'OwnAMIID',
            {
                mapping: {
                    "us-east-2": {
                      "ID": "ami-xxxxxxxx"
                    },
                    "us-east-1": {
                      "ID": "ami-yyyyyyyy"
                    }
                  }
            }
        )
        const ec2 = new CfnInstance(this, 'EC2', {
            imageId: Fn.findInMap(
                'OwnAMIID',
                this.region,
                'ID'
            )
        })
    }
}

// Initialize Stack by AWS CDK
const stack = new DevStack(new App(), 'test')

// Convert to CloudFormation template
const cfn = SynthUtils.toCloudFormation(stack)

// STDOUT
console.log(JSON.stringify(cfn))  

Then, we can get template to execute the Script file using ts-node.

% npx ts-node bin/dev.ts | jq .
{
  "Mappings": {
    "OwnAMIID": {
      "us-east-2": {
        "ID": "ami-xxxxxxxx"
      },
      "us-east-1": {
        "ID": "ami-yyyyyyyy"
      }
    }
  },
  "Resources": {
    "EC2": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": {
          "Fn::FindInMap": [
            "OwnAMIID",
            {
              "Ref": "AWS::Region"
            },
            "ID"
          ]
        }
      }
    }
  }
}

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts