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.