Last Updated: February 25, 2016
·
1.972K
· brunochauvet

Create an AWS Stack with cfndsl

Handcoding your json CloudFormation Template is no fun, so you decide to use cfndsl. Great. But cfndsl outputs the template to the console so you need to work around that to push your template to AWS.

A pretty basic cfndsl template (template.rb)

CloudFormation {
  AWSTemplateFormatVersion "2010-09-09"
  Description "My Stack"

  Parameter("InstanceType") {
    Description "Type of EC2 instance to launch"
    Type "String"
    Default "m1.medium"
  }

  Resource("Ec2Instance") {
    Type "AWS::EC2::Instance"
    Property("InstanceType", "t1.micro")
    ...
  }

}

... that you evaluate with cfndsl and redirect the output to a string instead of the standard output.

def generate_template
    results = $stdout = StringIO.new

    template = CfnDsl::CloudFormationTemplate.new
    template.instance_eval(File.read('template.rb'), 'template.rb')

    results.close_write
    results.rewind
    $stdout = STDOUT

    results.read
  end

Now you can push your json template to AWS and have your stack created.

require 'cfndsl'
require 'aws-sdk'
require 'stringio'

def create_stack
    client = AWS::CloudFormation::Client.new(region: 'ap-southeast-2')
    client.create_stack(stack_name: 'MyStack', template_body: generate_template)
end

3 Responses
Add your response

Great, thanks!

over 1 year ago ·

How about a followup on how you organize your DSL scripts!

over 1 year ago ·

Hey Bruno, this is not working using Ruby 2.1 and cfndsl 0.1.6.

A very terse and simple example of how we got it working now is

require 'cfndsl'

def generate_template
    model = CfnDsl::eval_file_with_extras('template.rb')
    model.to_json   
end
over 1 year ago ·