Blossom Logo Deploy your apps with Heroku-like simplicity using Blossom See Your Savings
BoltOps Logo
Lono CloudFormation Framework Introduction Part 8: Helpers header image

Lono CloudFormation Framework Introduction Part 8: Helpers

Tung Nguyen Tung Nguyen · February 17, 2020
3 min read

Today, we’ll learn about lono helpers. Lono helpers allow you to extend and add to the Lono DSL as a first-class citizen. This particularly makes Lono powerful because you can write methods specific to your needs.

Example

Generally, I’ve found that refactoring the resource methods into helpers makes the template clearer to understand. We’ll use the demo project from the previous post. Let’s create aec2_helper.rb to clean it up.

app/helpers/ec2_helper.rb

module Ec2Helper
  def instance(n)
    resource("Instance#{n}", "AWS::EC2::Instance",
      InstanceType: ref("InstanceType"),
      ImageId: find_in_map("AmiMap", ref("AWS::Region"), "Ami"),
      SecurityGroupIds: [get_att("SecurityGroup#{n}.GroupId")],
      UserData: base64(sub(user_data("bootstrap.sh")))
    )
  end

  def security_group(n)
    resource("SecurityGroup#{n}", "AWS::EC2::SecurityGroup",
      GroupDescription: "demo security group",
    )
  end
end

All we did was put each resource in a method. Now update demo.rb with the new helper methods.

@instance_count ||= 1 # default to 1
@instance_count.times do |i|
  n = i + 1
  instance(n)
  security_group(n)
end

Looking at the demo template, it’s clear that an instance and security group will be created.

Deploy

Let’s deploy:

lono cfn deploy demo

Here’s the CloudFormation console:

And the ec2 console:

Summary

In this post, we used helpers to clean up the template and move the resources to the ec2_helper.rb. By doing so, it makes the template quick and easy to understand. You can immediately tell that the blueprint creates an ec2 instance and security group.

Interestingly, I usually only refactor resources into helpers. I’ve found it’s helpful to keep everything else at the top-level template. This makes it easy to scan the entire template and quickly understand how everything works.

Lono Introduction Series

Blossom Logo
Deploy Your Apps with Ease

Blossom lets you deploy to your own servers with Heroku-like simplicity. Connect any cloud provider and we'll handle the rest. Save time and money with Blossom.

BoltOps Blog
Join a group of good-looking folks who get free email updates from BoltOps.