Let's Talk AWS
Intro to IaC on AWS with CloudFormation
A short introduction to infrastructure as code within AWS using CloudFormation.
By George Turner
Tue Oct 15 2024 · less than 3 min readJoin the Newsletter
Get the latest AWS news, tutorials, and resources delivered straight to your inbox every week.
AWS CloudFormation is an infrastructure as code solution similar to terraform, it simplifies the creation and management of AWS resources by enabling you to define your infrastructure within a YAML or JSON template.
How does CloudFormation work?
Once you have defined the YAML or JSON template, you can create a CloudFormation stack, which a region based concept which will manage the whole lifecycle of the resources defined within the template along with the parameter values and outputs. You can reuse the same template within multiple stacks to deploy the same or similar resources across multiple regions or accounts.
So what does a CloudFormation template contain?
CloudFormation templates are made up of 7 sections, Parameters, Rules, Mappings, Conditions, Transforms, Resources and Outputs, all of which are optional aside from Resources.
The Resources section is where the core of the configuration lies, let's consider how we would go about creating an EC2 instance. Each resource has three separate requirements, first you'll provide a name for the resource, then a resource type which in this case is AWS::EC2::Instance, along with a set of properties. For an EC2 instance we'll provide the ImageId, Instance Type along with a storage configuration to start and within this short configuration we've defined an EC2 instance which we can go ahead a deploy by creating a CloudFormation stack via the CLI or AWS Console.
Here's an example configuration;
Why should we define create our infrastructure this way instead of via the AWS console?
By defining and creating infrastructure through code you can simplify the management of infrastructure, for example, when it comes time to delete resources, you can do it with a couple of clicks or a single command whereas if you manually create the resources you'd have to delete each resource individually which increases the likelihood of mistakes being made.
Another reason is repeatability, IaC enables you to deploy the same set of infrastructure to multiple regions or accounts while reducing potential for misconfigurations and finally you have the ability to keep your infrastructure configuration in your preferred source control system to enable code reviews as well as automate security scanning and deployments with CI/CD Pipelines.