CloudFormationをyamlで書く話【cloudpack大阪ブログ】

CloudFormatinoを書く時の""と{}と,がストレスで辛い。と呟いたら、弊社スーパーエンジニアの以下の記事を教えてもらったので
CloudFormationのjsonがどうyamlに変わるのか、ちゃんとCFnとして食えるのか早速試した。
qiita.com

1. まずはEC2を作るサンプルテンプレート(ec2.json)を準備

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "WebGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "http 80",
        "SecurityGroupIngress": [{
          "IpProtocol" : "tcp",
          "CidrIp" : "0.0.0.0/0",
          "FromPort" : "80", "ToPort" : "80"
        }]
      }
    },
    "WebServer" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "ImageId" : "ami-f80e0596",
        "InstanceType" : "t2.micro",
        "SecurityGroupIds" : [
          { "Ref" : "WebGroup" }
        ]
      }
    },
    "WebServerEip": {
      "Type": "AWS::EC2::EIP",
      "Properties": {
        "InstanceId": { "Ref": "WebServer" }
      }
    }
  }
}

2. ec2.jsonを食わせて、ec2.ymlを出力

j2y -o ec2.yml ec2.json

3. 出力結果はこちら。なるほど、スッキリしました。(ec2.yml)

AWSTemplateFormatVersion: 2010-09-09
Resources:
  WebGroup:
    Properties:
      GroupDescription: http 80
      SecurityGroupIngress:
      - CidrIp: 0.0.0.0/0
        FromPort: "80"
        IpProtocol: tcp
        ToPort: "80"
    Type: AWS::EC2::SecurityGroup
  WebServer:
    Properties:
      ImageId: ami-f80e0596
      InstanceType: t2.micro
      SecurityGroupIds:
      - Ref: WebGroup
    Type: AWS::EC2::Instance
  WebServerEip:
    Properties:
      InstanceId:
        Ref: WebServer
    Type: AWS::EC2::EIP

4. ec2.ymlを食わせて、ec2a.jsonを出力

j2y -o ec2a.json -r ec2.yml

5. 出力結果はこちら。キレイに整形してくれました(ec2a.json

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "WebGroup": {
      "Properties": {
        "GroupDescription": "http 80",
        "SecurityGroupIngress": [
          {
            "CidrIp": "0.0.0.0/0",
            "FromPort": "80",
            "IpProtocol": "tcp",
            "ToPort": "80"
          }
        ]
      },
      "Type": "AWS::EC2::SecurityGroup"
    },
    "WebServer": {
      "Properties": {
        "ImageId": "ami-f80e0596",
        "InstanceType": "t2.micro",
        "SecurityGroupIds": [
          {
            "Ref": "WebGroup"
          }
        ]
      },
      "Type": "AWS::EC2::Instance"
    },
    "WebServerEip": {
      "Properties": {
        "InstanceId": {
          "Ref": "WebServer"
        }
      },
      "Type": "AWS::EC2::EIP"
    }
  }
}

6. ec2a.jsonをCFnに突っ込んでみる。問題なくデプロイできた

f:id:xwkns157:20160416115033p:plain

7. まとめ

1. yamlからjsonに変換しても問題なくCFnにデプロイ出来た
2. 正直yamlでもjsonでも書くこと変わらないが、""、{}、,が無くなったのでコードがスッキリし、行数が明らかに減った
3. いちいち""、{}、,を気にしなくていいのでストレス減りそう
4. yamlはインデント等は気にする必要あるが、jsonでもインデントしないと見辛い
5. これは捗りそう

ちなみに作成途中のCloudFormationの行数が1/3ほど減った

$ wc -l CFn-test2.json
     671 CFn-test2.json
$ wc -l CFn-test2.yml
     471 CFn-test2.yml