Lono CloudFormation Framework Introduction Part 8: Helpers
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
Thanks for reading this far. If you found this article useful, I'd really appreciate it if you share this article so others can find it too! Thanks 😁 Also follow me on Twitter.
Got questions? Check out BoltOps.
You might also like
More tools:
-
Kubes
Kubes: Kubernetes Deployment Tool
Kubes is a Kubernetes Deployment Tool. It builds the docker image, creates the Kubernetes YAML, and runs kubectl apply. It automates the deployment process and saves you precious finger-typing energy.
-
Jets
Jets: The Ruby Serverless Framework
Ruby on Jets allows you to create and deploy serverless services with ease, and to seamlessly glue AWS services together with the most beautiful dynamic language: Ruby. It includes everything you need to build an API and deploy it to AWS Lambda. Jets leverages the power of Ruby to make serverless joyful for everyone.
-
Lono
Lono: The CloudFormation Framework
Building infrastructure-as-code is challenging. Lono makes it much easier and fun. It includes everything you need to manage and deploy infrastructure-as-code.