Estimate project
← All posts

Infrastructure as code (IaC) – what it is and why it should matter to me

The term IaC has been around for ages and isn't much of a trend anymore. Find out why it remains a compelling subject and why it deserves your attention.

9 min read
Infrastructure as codeDevOpsTerraformCloudIaC

Introduction

I’m convinced this term has been in use for so long that somewhere along the way it lost its meaning. Not so long ago it was a buzzword; today it isn’t. Even though it’s falling out of fashion, I’ll do my best to cover the topic, because it matters as much as it ever did.

Let’s begin at the very start. Picture yourself running your first serious project in the cloud. For weeks it’s been stable and doing great. Then, at some point, you notice that traffic to your app has jumped within a very short time. All of a sudden, more people seem to be trying to use it. What do you do? You open the AWS console and add another virtual machine to your load balancer, naturally. And this keeps happening, because your app is a hit and people all over the world are spreading the word about it.

Eventually you realize this is anything but efficient, since you spend a great deal of time managing your infrastructure through the UI, clicking all kinds of buttons and jumping between pages. As a developer, you wish you could build infrastructure the same way you build software. You might, for example, write a description of a VM and specify its properties such as CPU type, amount of memory, disk type and capacity, and so on. In short, you’d like to be able to deploy infrastructure declaratively.

As it happens, others have already had that idea. But you might ask…

Why bother?

To me, the greatest benefit is consistency. Once infrastructure has been described, it should remain unchanged. Any drift that appears (thanks, entropy!) gets brought back in line with the specification stored in a fairly simple text file. In fact, it makes no difference whether something happens because of a user-triggered event, some sort of failure or a mistake made by a teammate – with IaC, recovery should be easy. You can think of it as a lightweight snapshot you can roll back to. It gets even simpler with GitOps.

Well-written code brings one more benefit – reusability. Anything described in code can be reused later on. Need one more environment? Or perhaps a copy of the one you’ve just set up? Easy! With some forward planning, you can write the code for deploying container clusters, databases, caches and image registries as modules. The next time you build an environment from code, you simply reference those modules and supply the required parameters. Trust me, this will save you plenty of time.

How to choose a tool?

A wide range of tools implement infrastructure as code. I won’t go into the details too deeply, as that’s beyond the scope of this article. Today the key differences lie in the templating a tool uses (e.g., Jinja in Ansible, Embedded Ruby in Puppet and Chef, HCL in Terraform), in how the configuration gets applied (the config is pulled from a controlling server, as in Chef, or pushed to the controlled infrastructure, as in Ansible and Terraform) and in the language the tool itself is written in. Expect differences as well in how they handle secrets and state files and how they group the resources they manage.

It’s worth pointing out that some of these tools are better at configuration management than at provisioning infrastructure, and the other way round. Put differently, not every tool is as good at creating the required resources as it is at configuring them. Personally, I think Terraform does better at provisioning infrastructure (especially in the cloud), while Ansible does better at configuring virtual machines.

These days most of the tools listed above support every kind of environment, bare metal servers and public cloud resources included. It should be noted that some of them were built with particular functionality in mind and were extended over time to support other things – Chef’s AWS support is one such example. Tools that came out of a public cloud offering are a separate case. CloudFormation (AWS), AWS CDK (AWS, obviously) and Bicep (Azure) can’t be extended for use anywhere else.

Then again, if you’re completely sure you’ll never leave your current cloud, they’re worth considering. The public cloud team will update them the fastest whenever the cloud API changes, so you won’t have to wait for the community to release an update.

Having said that, I think Terraform is a safe choice whatever your cloud plans. In Stack Overflow’s annual survey, Terraform was the IaC tool respondents named most often, and it’s certainly a sound option if you intend to deploy infrastructure to a popular cloud such as AWS or Azure. For deployments to GCP, Terraform is in fact the tool Google recommends.

Terraform?

Let me say a few words about Terraform and why it’s so popular nowadays. It’s an infrastructure management tool that takes a declarative approach and uses HCL (HashiCorp Configuration Language) to write infrastructure definitions.

Its flexibility comes from the wide choice of providers that talk to external systems such as public clouds, APIs and so on. Providers ship both with the official distribution and as modules built by the lively Terraform community. As a result, users can create resources with one consistent syntax. The provider hides the implementation details, which keeps the code simpler. Naturally, small differences depend on the specific environment, but the engineering value is enormous.

What’s more, Terraform keeps its whole configuration in a state file, which has several advantages. Above all, it lowers the risk of accidental deletion, as the state file is treated as the source of truth for all infrastructure managed by Terraform. And if we keep the state file in object storage, we can share it with colleagues without effort and manage the infrastructure as a team.

A minimal piece of Terraform code might look like this:

provider "aws" {
  region = "eu-west-1"
}

resource "aws_instance" "instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "DemoInstance"
  }
}

Here we declare that we’ll use the aws provider, which provisions resources on AWS. Our EC2 instance is to be deployed in the eu-west-1 region. Next, we instruct Terraform to use a particular AMI (Amazon Machine Image) ID, and we pick the small t2.micro type, since this is just a test and nothing fancy is needed. Finally, we ask Terraform to add a tag Name with the value DemoInstance. Once Terraform has our AWS credentials, we can run terraform init to download the provider we need. After that, we should be ready to run theterraform plan. Before creating anything, Terraform will show us what it intends to do.

iac ➤ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create

Terraform will perform the following actions:

# aws_instance.instance will be created
+ resource "aws_instance" "instance" {
      + ami                                  = "ami-0c55b159cbfafe1f0"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_lifecycle                   = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + spot_instance_request_id             = (known after apply)
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "Name" = "DemoInstance"
        }
      + tags_all                             = {
          + "Name" = "DemoInstance"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id                 = (known after apply)
              + capacity_reservation_resource_group_arn = (known after apply)
            }
        }

      + cpu_options {
          + amd_sev_snp      = (known after apply)
          + core_count       = (known after apply)
          + threads_per_core = (known after apply)
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + instance_market_options {
          + market_type = (known after apply)

          + spot_options {
              + instance_interruption_behavior = (known after apply)
              + max_price                      = (known after apply)
              + spot_instance_type             = (known after apply)
              + valid_until                    = (known after apply)
            }
        }

      + maintenance_options {
          + auto_recovery = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_protocol_ipv6          = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_card_index    = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + private_dns_name_options {
          + enable_resource_name_dns_a_record    = (known after apply)
          + enable_resource_name_dns_aaaa_record = (known after apply)
          + hostname_type                        = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Clearly, Terraform fills in most of the fields automatically once we run terraform apply. To tidy up, we can run terraform destroy, which removes only the resources recorded in the state file.

Don’t delay, introduce IaC today!

Any moment is a good moment to bring infrastructure as code into your team. Starting development with it from day one is certainly easier, but the earlier you adopt it, the better. At our company, IaC is a standard practice that lets us work efficiently.