Nathan Peck
Nathan Peck
Senior Developer Advocate at AWS
 Jul 14, 2023 7 min read

Why use infrastructure as code?

Infrastructure as code is the process of provisioning and managing your cloud resources by writing a template file that describes what infrastructure you want to create. The template file is both human readable, as well as machine consumable. Humans write or edit the file in order to change what infrastructure they would like in their cloud deployment. An infrastructure as code service then makes automated API calls to actually create or update the infrastructure to match what the infrastructure as code template requested.

An infrastructure as code analogy

Infrastructure as code is like a shopping list, and the infrastructure as code service is your professional shopper:

This professional shopper only understands YAML. So first you write a YAML list of requirements for your refrigerator contents. It might look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
RefrigeratorContents:

  - Type: eggs
    Quantity: 12
    Properties:
      Size: Large
      Organic: true
      ShellColor: brown

  - Type: carrot
    Quantity: 1

  - Type: bread-loaf
    Quantity: 1
    Properties:
      BreadVariety: baguette

Now your professional shopper compares this list of required refrigerator contents against the actual current contents of your refrigerator. They will take note of any missing items or items that don’t match your description.

For example they might see that you only have 8 eggs instead of 12. Therefore the shopper knows that they need to add 4 eggs to your refrigerator. They might see that you already have 1 carrot so there is no need to make any changes there. Or they might see that you have a bread loaf but it is rye bread instead of a baguette, therefore the bread loaf needs to be replaced by a new loaf that matches your requirements.

The professional shopper goes to the grocery store for you and buys any items required to update the refrigerator contents to match your list of requirements. They put your requested items into your refrigerator, and remove any unwanted items that weren’t on the list.

In this analogy you can see how the professional shopper makes it easier for you to manage the contents of your refrigerator. You just write a list of what you want in your refrigerator and have it off to the professional shopper. You no longer have to go to the grocery store, buy groceries, or unload them into your refrigerator. The professional shopper is even cleaning out old unwanted items from the refrigerator as well.

Infrastructure as code does the same thing for you when deploying to the cloud. The cloud is your refrigerator, and cloud services and resources are items on your infrastructure as code grocery list.

Infrastructure as Code with CloudFormation

There are a variety of different infrastructure as code options.

For AWS cloud development the built-in choice for infrastructure as code is AWS CloudFormation.

Using AWS CloudFormation you can write a description of the resources that you want to create on your AWS account, and then ask AWS CloudFormation to make this description into reality. For example the following YAML template snippet describes an AWS ECS service resource to create:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Service:
  Type: 'AWS::ECS::Service'
  DependsOn: 'ServiceDiscoveryService'
  Properties:
    ServiceName: 'app'
    Cluster: 'production'
    DeploymentConfiguration:
      MaximumPercent: 200
      MinimumHealthyPercent: 75
    DesiredCount: 5
    TaskDefinition: !Ref 'TaskDefinition'
    ServiceRegistries:
      - RegistryArn: !GetAtt ServiceDiscoveryService.Arn
        ContainerPort: 3000
        ContainerName: 'myapp'

AWS CloudFormation takes this template and assumes the responsibility of creating, updating, and deleting resources on your AWS account according to what is described in the template. If you add a new resource to the file CloudFormation will create that resource on your account. If you update a resource CloudFormation will update or replace any existing matching resources. And if you remove a resource from the template it will be cleaned up and removed from your AWS account.

Generated Infrastructure as Code

Another way to use infrastructure as code is with an infrastructure as code generator. Think of this as similar to ordering cooked food from a restaurant.

When you order from a restaurant you place your order for a cooked meal, but you trust the restaurant to decide the ingrediants, actually do the ingrediant shopping for you on your behalf, and cook the meal. You just get the cooked meal back from the kitchen.

This is similar to using an infrastructure as code generator. The generator allows you to describe what type of infrastructure you want at a higher level. For example you could say “I would like a load balanced web server”. Then the infrastructure as code generator provisions all the resources necessary for a load balanced web server on your behalf. You just get a deployed URL back.

There are a couple popular infrastructure as code generators for containers on AWS:

  • AWS Cloud Development Kit - This is a programming language SDK that is ideal for developers who want to self deploy their own applications. AWS CDK lets you instantiate “constructs” such as ApplicationLoadBalancedFargateService. A construct wraps multiple AWS resources and their configurations up into one neat prebuilt package that you can deploy onto your AWS account.
  • AWS Copilot - The official CLI tool for Amazon ECS. It has a wizard like flow that asks you questions about what you would like to deploy and then generates and deploys AWS CloudFormation on your behalf. It also provides local development assistance such as building Dockerfiles into images and pushing them automatically, and setting up automatic continous delivery pipelines that rebuild and redeploy your code whenever you push a commit to your code repository.

Benefits of infrastructure as code

Infrastructure as code brings a lot of benefits:

  • Visibility: An infrastructure as code template serves as a very clear reference of what resources are on your account, and what their settings are. You don’t have to navigate the web console to check the parameters.
  • Stability: If you accidentally change the wrong setting or delete the wrong resource in the web console you can break things. Infrastructure as code helps solve this, especially when it is combined with version control, such as Git.
  • Scalability: With infrastructure as code you can write it once and then reuse it many times. This means that one well written template can be used as the basis for multiple services, in multiple regions around the world, making it much easier to horizontally scale.
  • Security: Infrastructure as code gives you a unified template for how to deploy your architecture. If you create one well secured architecture you can reuse it multiple times, and know that each deployed version is following the same settings.
  • Transactional: CloudFormation not only creates resources on your AWS account but also waits for them to stabilize while they start. It verifies that provisioning was successful, and if there is a failure it can gracefully roll the infrastructure back to a past known good state.

Benefits of infrastructure as code generation

  • Concise: Rather than needing to decide every detail you can just decide on the details that matter the most to you and let your infrastructure as code generator fill in the rest. In many cases you can write 20-30 lines of infrastructure as code for a generator, and it will generate 100’s of lines of lower level YAML for an infrastructure as code service.
  • Up to date: As best practices change and new features are added to AWS cloud services, the infrastructure as code generator will update how it generates infrastructure to fulfill your request. This allows you to keep up with the best and latest features of AWS by doing one update to the version of your infrastructure as code generator, rather than manually updating 100’s of lines of infrastructure as code.

Conclusion

Are you ready to get started with infrastructure as code on AWS? This website contains a collection of prebuilt infrastructure as code patterns that you can deploy as is, or use as a starting point for your own customized infrastructure as code. You will find examples and instructions for a variety of infrastructure as code services and infrastructure as code generators.

Visit the infrastructure as code patterns collection to get started.