Why use infrastructure as code?

Infrastructure as code is the process of provisioning and managing your cloud resources by writing a template file that is both human readable, and machine consumable. 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:

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 then 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 either 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.

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 to 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: Once again 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.