Skip to content
ImagineWorld

Leveraging Infrastructure as Code

node_idnode-book_the-linux-devops-handbook_chapter-12-leveraging-infrastructure-as-code
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleLeveraging Infrastructure as Code
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Leveraging Infrastructure as Code

Section titled “Chapter 12 — Leveraging Infrastructure as Code”

In today’s digital landscape, managing and deploying infrastructure is a complex and time-consuming process. Traditionally, infrastructure deployment involves manually configuring each server, network, and storage device. This process is not only time-consuming but also prone to errors and inconsistencies. Infrastructure as Code (IaC) solutions provide an automated way to manage and deploy infrastructure. IaC solutions allow developers to treat infrastructure as code, enabling them to define, manage, and provision infrastructure in the same way they do with code.

In this chapter, we will explore IaC solutions, with a focus on Terraform. Terraform is an open source IaC tool that enables developers to define, manage, and provision infrastructure across multiple cloud providers and on-premises data centers. HashiCorp, the owner of Terraform and many other automation tools, changed the license from Mozilla Public License (MPL) version 2.0 to Business Source License (BSL) version 1.1. BSL allows you to use Terraform freely and you can access its source code, so there is no change for the end users.

With Terraform, developers can write code to define their infrastructure requirements, and Terraform will handle the provisioning and configuration of the required resources. Terraform has gained popularity in recent years due to its simplicity, flexibility, and support for multiple cloud providers. In the following sections, we will discuss the key features and benefits of Terraform, as well as how to use it to provision infrastructure on popular cloud providers.

We will learn about the following topics in this chapter:

  • What is IaC?
  • IaC versus Configuration as Code
  • IaC projects worth knowing
  • Terraform
  • HCL in depth
  • Terraform examples with AWS

For this chapter, you will need a system capable of running Terraform. Terraform is a single binary program written in the Go programming language. Its installation is straightforward and is explained on the HashiCorp Terraform project page (https://developer.hashicorp.com/terraform/downloads). HashiCorp is the company behind Terraform and other cloud management tools that have become de facto standards in the DevOps world. You will also need an AWS account. AWS provides a Free Tier of services for a limited time. We are using services that have free tiers at the time of writing this book. Before you run the examples, please consult the AWS Free Tier listing to avoid unnecessary costs.

IaC is a software development practice that involves defining and managing infrastructure through code. In essence, it means that infrastructure is treated as if it were a piece of software, and is managed through the same processes and tools. IaC solutions enable developers to define, provision, and manage infrastructure using code, instead of manually configuring servers, networks, and storage devices. This approach to infrastructure management is highly automated, scalable, and efficient, allowing organizations to reduce deployment times and improve consistency and reliability.

IaC solutions come in different forms, including configuration management tools, provisioning tools, and cloud orchestration tools. Configuration management tools, such as Ansible and Chef, are used to manage the configuration of individual servers or groups of servers. Provisioning tools, such as Terraform and CloudFormation, are used to provision and configure infrastructure resources. Cloud orchestration tools, such as Kubernetes and OpenShift, are used to manage containerized applications and their associated infrastructure. Regardless of the specific tool used, IaC solutions offer several benefits, including repeatability and consistency.

You might be wondering, didn’t we just cover this in Chapter 11, when we spoke about Ansible? The answer is no, we didn’t. There’s a very distinctive difference between IaC and Configuration as Code (CaC). IaC tools are concerned with exactly that: infrastructure. This means networking, DNS names, routes, and servers (VM or physical) up to the installation of the operating system. CaC is concerned with what lives inside the operating system. People try to use one tool for everything, so you’ll see modules for Ansible that can configure switches and routers, but the tool shines best where it is intended to be used. Nobody is going to die if you mix these two, but your life will become more difficult.

Since the rise of the public cloud, especially AWS, the need for a repeatable and reliable way of setting up an infrastructure and configuring cloud services started to grow as well. Since then, a lot of tools have come to be and more of them are being developed. In this section, we will review the most popular and innovative tools out there.

AWS CloudFormation is a popular IaC tool offered by Amazon Web Services (AWS) to automate the provisioning of AWS resources. It was first released in 2011 and has since become a widely used tool for managing infrastructure in the cloud.

CloudFormation allows you to define the infrastructure in a declarative language, such as YAML or JSON, and then create, update, or delete stacks of resources based on those definitions. This allows for consistent and reproducible infrastructure deployments, as well as easy rollback and version control. It’s not all sparkles and rainbows, though – at times, you might find yourself stuck in a rollback loop after making an untested change. For example, let’s say you’re changing your AWS Lambda environment version. Unfortunately, it failed as the version you’re currently using is no longer supported. So, it is now stuck at rolling back and it’s in an UPDATE_ROLLBACK_FAILED state. You will need to resolve the issue by hand as there is no automated way of doing that.

CloudFormation integrates with other AWS services, such as AWS Identity and Access Management (IAM), AWS Elastic Load Balancing (ELB), and AWS Auto Scaling, to enable the creation of complex architectures with ease.

Here’s an example CloudFormation stack written in YAML that creates an EC2 instance called t4g.small in a public subnet in the default VPC:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
KeyName:
Type: AWS::EC2::KeyPair::KeyName
Default: admin-key
InstanceType:
Type: String
Default: t4g.small
SSHCIDR:
Type: String
MinLength: 9
MaxLength: 18
Default: 0.0.0.0/0
AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
LatestAmiId:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/canonical/ubuntu/server/jammy/stable/current/amd6/hvm/ebs-gp2/ami-id'
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref 'InstanceType'
SecurityGroups: [!Ref 'InstanceSecurityGroup']
KeyName: !Ref 'KeyName'
ImageId: !Ref 'LatestAmiId'
InstanceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: !Ref 'SSHCIDR'
Outputs:
InstanceId:
Description: InstanceId of the newly created EC2 instance
Value: !Ref 'EC2Instance'
PublicDNS:
Description: Public DNSName of the newly created EC2 instance
Value: !GetAtt [EC2Instance, PublicDnsName]
PublicIP:
Description: Public IP address of the newly created EC2 instance
Value: !GetAtt [EC2Instance, PublicIp]

In this stack, we’re creating two resources: an EC2 instance and a security group attached to this instance. The CloudFormation stack can get four parameters:

  • KeyName: The SSH key name that was already created inside the AWS EC2 service. This defaults to admin-key.
  • InstanceType: The type of the instance we want to start with. It defaults to t4g.small.
  • SSHCIDR: The Classless Inter-Domain Routing (CIDR) of IP address(es) that can connect to this machine via port 22. This defaults to 0.0.0.0/0. Here, we’re validating the provided input against the regular expression and the length of the variable.
  • LatestAmiId: The AMI ID to use as a base system to start the EC2 instance. This defaults to the latest AMI of Ubuntu Linux 22.04.

Next, there’s a Resources section. Here, the EC2 instance is created using the AWS::EC2::Instance resource type and the security group is created with the AWS::EC2::SecurityGroup resource.

The final section is called Outputs; here, we can reveal IDs and other properties of the resources created. Here, we’re exposing the instance ID, its public DNS name, and its public IP address.

It’s possible to use these output values as input for another CloudFormation stack, which will make the YAML files of your CloudFormation code considerably smaller and easier to maintain.

AWS Cloud Development Kit (CDK) is an open source software development framework that’s used to define cloud infrastructure in code. With CDK, developers can write code in familiar programming languages such as TypeScript, Python, Java, C#, and JavaScript to create and manage cloud resources on AWS.

AWS CDK was first released in July 2018 as an open source project by AWS. It was designed to simplify the process of building and deploying cloud infrastructure by allowing developers to use their existing programming language skills and tools. With CDK, developers can define IaC and take advantage of the benefits of version control, automated testing, and continuous integration / continuous deployment (CI / CD) pipelines. Since its release, CDK has become a popular choice for building infrastructure on AWS, and it continues to receive updates and new features to this day.

Here’s an example of some AWS CDK Python code that creates an EC2 instance:

from aws_cdk import core
import aws_cdk.aws_ec2 as ec2
class MyStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# VPC
vpc = ec2.Vpc(self, "VPC",
nat_gateways=0,
subnet_configuration=[ec2.SubnetConfiguration(name="public",subnet_type=ec2.SubnetType.PUBLIC)]
)
# Get AMI
amzn_linux = ec2.MachineImage.latest_amazon_linux(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
edition=ec2.AmazonLinuxEdition.STANDARD,
virtualization=ec2.AmazonLinuxVirt.HVM,
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)
# Create an EC2 instance
instance = ec2.Instance(self, "Instance",
instance_type=ec2.InstanceType("t4g.small"),
machine_image=amzn_linux,
vpc = vpc
)

This code creates a new VPC and an EC2 instance with an instance type of t4g.small with Amazon Linux installed as the operating system. Note that you will need to have AWS CDK installed and configured to run this code.

Terraform is a popular open source tool that’s used for infrastructure automation, specifically for creating, managing, and provisioning cloud resources. It enables developers to define their IaC and automates the deployment of their infrastructure across multiple cloud platforms. With Terraform, users can write declarative configuration files in a simple and intuitive language that can be versioned, shared, and reused. This approach to infrastructure management ensures consistency and scalability and reduces the risk of manual errors. Terraform supports a wide range of cloud providers, including AWS, Azure, Google Cloud, and more, making it a popular choice for organizations with complex cloud infrastructure needs.

Terraform was created by HashiCorp, a company founded in 2012 by Mitchell Hashimoto and Armon Dadgar. The company is known for developing popular open source tools for infrastructure automation, including Vagrant, Consul, Nomad, and Vault. Terraform was first released in July 2014 and has since become one of the most widely adopted IaC tools in the industry. HashiCorp continues to maintain and develop Terraform, with regular releases and updates that address new cloud provider features, security vulnerabilities, and community feedback. The tool has a large and active community of contributors, which has helped to further enhance its functionality and support for new use cases.

Terraform is also a main topic for this chapter, so we will dig into the code and its internals in the Terraform section later.

Cloud Development Kit for Terraform (CDKTF) is an open source software development framework for defining cloud infrastructure in code. It allows users to define infrastructure using familiar programming languages, such as TypeScript, JavaScript, Python, and C#. This provides developers with more flexibility and control over their infrastructure as they can leverage their existing programming skills and tools to define complex infrastructure. CDKTF was first released in 2019 as a collaboration between AWS and HashiCorp. Since then, it has gained popularity as a powerful tool for defining and deploying infrastructure using Terraform.

CDKTF supports a wide range of programming languages, making it easy for developers to use their preferred language. It uses constructs, which are reusable building blocks that represent AWS resources, to create infrastructure. Users can define constructs for each resource they want to create, which can be combined to form a more complex infrastructure. This allows users to define their infrastructure in a modular and reusable way, which simplifies the process of creating and maintaining infrastructure over time.

Here is the example code for creating an EC2 instance in AWS using CDKTF in Python:

from constructs import Construct
from cdktf import App, TerraformStack
from imports.aws import AwsProvider, Instance, SecurityGroup
class MyStack(TerraformStack):
def __init__(self, scope: Construct, ns: str):
super().__init__(scope, ns)
# Configure AWS provider
aws_provider = AwsProvider(self, 'aws', region='us-east-1')
# Create a security group
security_group = SecurityGroup(self, 'web-server-sg',
name='web-server-sg',
ingress=[
{
'from_port': 22,
'to_port': 22,
'protocol': 'tcp',
'cidr_blocks': ['0.0.0.0/0'],
},
{
'from_port': 80,
'to_port': 80,
'protocol': 'tcp',
'cidr_blocks': ['0.0.0.0/0'],
},
],
)
# Create an EC2 instance
Instance(self, 'web-server',
ami='ami-0c55b159cbfafe1f0',
instance_type='t4g.small',
security_groups=[security_group.id],
user_data="""
#!/bin/bash
echo "Hello, DevOps People!" > index.html
nohup python -m SimpleHTTPServer 80 &
"""
)
app = App()
MyStack(app, "my-stack")
app.synth()

The constructs, App, and TerraformStack classes are imported from the cdktf package, while the AWS resources are imported from the imports.aws module. The preceding code creates an EC2 instance with a security group and a basic user data script that starts a simple HTTP server. The resulting infrastructure can be deployed using the cdktf deploy command, which generates Terraform configuration files and executes the Terraform CLI.

You can read more about CDKTF at https://developer.hashicorp.com/terraform/cdktf.

Pulumi is an open source IaC tool that allows developers to build, deploy, and manage cloud infrastructure using familiar programming languages. Unlike traditional IaC tools that rely on declarative languages such as YAML or JSON, Pulumi uses real programming languages, such as Python, TypeScript, Go, and.NET, to define and manage infrastructure. This enables developers to leverage their existing skills and experience to create infrastructure using the same tools and processes they use for building applications. With Pulumi, developers can create, test, and deploy infrastructure changes just like they do with code changes – that is, by using version control and CI/CD tools.

The first release of Pulumi was in May 2018 and aimed to simplify the process of managing cloud infrastructure. Pulumi was founded by Joe Duffy, a former Microsoft engineer who previously worked on the development of the.NET runtime and compiler. Duffy saw an opportunity to use programming languages to manage infrastructure, providing a more flexible and powerful approach than traditional IaC tools. Since its release, Pulumi has gained popularity among developers, particularly those who work in cloud-native environments or who use multiple cloud providers.

Pulumi supports a variety of programming languages, including Python, TypeScript, Go,.NET, and Node.js. Pulumi also provides a rich set of libraries and tools for working with cloud resources, including support for popular cloud providers such as AWS, Azure, Google Cloud, and Kubernetes. Additionally, Pulumi provides integrations with popular CI/CD tools, such as Jenkins, CircleCI, and GitLab, enabling developers to easily incorporate infrastructure changes into their existing workflows.

Here’s an example of Pulumi code in Python that creates an AWS EC2 instance:

import pulumi
from pulumi_aws import ec2
# Create a new security group for the EC2 instance
web_server_sg = ec2.SecurityGroup('web-server-sg',
ingress=[
ec2.SecurityGroupIngressArgs(
protocol='tcp',
from_port=22,
to_port=22,
cidr_blocks=['0.0.0.0/0'],
),
],
)
# Create the EC2 instance
web_server = ec2.Instance('web-server',
instance_type='t4g.small',
ami='ami-06dd92ecc74fdfb36', # Ubuntu 22.04 LTS
security_groups=[web_server_sg.name],
tags={
'Name': 'web-server',
'Environment': 'production',
},
)
# Export the instance public IP address
pulumi.export('public_ip', web_server.public_ip)

This code defines an AWS security group that allows inbound traffic on port 22 (SSH), and then creates an EC2 instance of the t4g.small instance type, using an Ubuntu 22.04 LTS AMI. The instance is associated with the security group we created earlier and is tagged with a name and environment. Finally, the public IP address of the instance is exported as a Pulumi stack output, which can be used by other resources in the stack or accessed by the user.

In this section, we introduced several IaC solutions: CDK, CDKTF, Terraform, and Pulumi. Some of them are targeted at one cloud provider, and some of them allow us to configure different cloud environments.

In the next section, we will get back to Terraform to explore what makes it tick and learn how to use IaC in practice. This will give us a foundation to quickly understand other solutions, including the CDKs we mentioned earlier.

In this section, we are going to introduce Terraform, one of the most widely used IaC solutions in the wild.

Terraform is an IaC tool developed by HashiCorp. The rationale behind using it is similar to using Ansible to configure your systems: infrastructure configuration is kept in text files. They are not YAML, as with Ansible; instead, they are written in a special configuration language developed by HashiCorp: HashiCorp Configuration Language (HCL). Text files are easily versioned, which means that infrastructure changes can be stored in a version control system such as Git.

Actions performed by Terraform are more complicated than those you’ve seen in Ansible. A single HCL statement can mean setting up a whole bunch of virtual servers and routes between them. So, while Terraform is also declarative like Ansible, it is higher level than other tools. Also, contrary to Ansible, Terraform is state-aware. Ansible has a list of actions to perform and on each run, it checks which actions have already been applied. Terraform, on the other hand, records the last achieved state of the system and each time it is executed, it ensures the system will be as it is in the code.

To achieve this, Terraform creates and maintains a state file. It is a text file with the .tfstate extension that records the last known state of the infrastructure that the tool is aware of. The state file is versioned internally; Terraform maintains a special counter that allows it to know whether the file is the latest one. The state file is essential for Terraform to work properly. You should never corrupt or lose the state file. If you lose this file, Terraform will try to create things that already exist and maybe delete things it should not.

There are several ways to ensure the state file is safe. One of them is to store it in an object store (such as S3) that’s been properly configured so that the state file cannot be deleted. For improved security, you can ensure that the file is versioned, which means that the storage will keep old copies of the file for eventual reuse.

There is one important thing to be aware of related to .tfstate: it will contain all information related to your infrastructure, as well as plaintext passwords, logins, access keys, and such. It is crucial to keep the file secret and exclude it from commits to version control systems (in Git, add it to the .``gitignore file).

The code is developed in text files with the .tf extension. Contrary to Ansible, again, the order in which you place directives in the files is not important. Before execution, Terraform analyzes all .tf files in the current directory, creates a graph of dependencies between configuration elements, and orders them properly. It is a common occurrence that code is broken down into smaller .tf files that group related configuration directives. However, nothing is stopping you from keeping them all in one huge file, though it will quickly become too big for comfortable use.

Even though you are free to name your files as you wish, so long as their extension is .tf, there are best practices to be observed:

  • main.tf: This is the main file where you develop your configuration code. It will contain the resources, modules, and other important information.
  • variables.tf: This file will contain declarations of all the variables you wish to use in the main.tf file.
  • outputs.tf: If the resources in your main.tf file produce any outputs, they are declared here.
  • versions.tf: This file declares the required versions of the Terraform binary itself and providers. It is good practice to declare the lowest versions known to work properly with your code.
  • providers.tf: If any of the providers need additional configuration, you would place them in this file.
  • backend.tf: This file contains the configuration for where Terraform should store the state file. The state file is an integral part of IaC in Terraform. We will talk about this in more depth in the Terraform state subsection.

The heavy lifting in Ansible is done by Python programs called modules. In Terraform, it is done by providers. Providers are small Golang programs that consume the configuration plan prepared by Terraform, connect with services (the cloud, devices, and more) through said services’ APIs, and execute the configuration. You can think of them as plugins. Providers deliver a set of resource types and, eventually, the data sources required to write configuration for the API that the provider connects to. The official explanation is that providers “ are a logical abstraction of an upstream API.” Providers are usually published on Terraform Registry, which is a public repository of plugins maintained by HashiCorp. You can use separate registries, but providers published on Terraform Registry are known to be tested and trusted to work properly. Each provider published on this registry has extensive documentation with well-commented examples. Whenever you are using a new provider, you should visit the registry (https://registry.terraform.io/). An example of a provider is AWS. This provider exposes a very extensive number of resources that you would use to interact with AWS services to provision and configure them. Remember: the configuration is limited to infrastructure. You can couple Terraform (to provision VMs, for example) with Ansible (to install software and configure it within the VM) for a full experience.

Let’s look at an example of an AWS provider from the Terraform Registry AWS provider documentation (https://registry.terraform.io/providers/hashicorp/aws/latest/docs):

terraform {
required_providers {
aws = {
source = "hashicorp/aws" version = "~> 4.0"
}
}
}
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
}
# Create a VPC
resource "aws_vpc" "example" {
cidr_block = "10.0.0.0/16"
}

In the preceding snippet, we declare that we require the AWS provider that will be downloaded from Terraform Registry. Its version should be no lower than 4.0. Then, we configure the region that we are going to use (us-east-1). Finally, we create a virtual private network (virtual private cloud (VPC)) and declare an IP block for it.

The set of .tf files in a single directory is called a module. If you run Terraform commands in the directory where module files lie, it is called a root module.

One of the key concepts in Terraform is the module. A Terraform module is a collection of resources and their dependencies that can be used to build a specific component of your infrastructure. Modules provide a way to organize your code and make it reusable across multiple projects. They can be shared with other users and teams, and even published to a public registry such as Terraform Registry.

When working with Terraform, it’s important to ensure that you are using compatible versions of your infrastructure provider. Providers are responsible for managing the resources in your cloud environment, and different versions may have different features or behaviors. To avoid unexpected changes to your infrastructure, you can pin the version of a provider that you are using in your Terraform configuration. This can be done by specifying a version constraint in the provider block, using the Terraform version constraint syntax. When you run Terraform, it will download and use the specified version of the provider, ensuring that your infrastructure remains consistent and predictable.

Here’s an example versions.tf file that pins the AWS provider to the latest version and requires at least version 1.0.0 of Terraform:

terraform {
required_providers {
aws = ">= 3.0.0"
}
required_version = ">= 1.0.0"
}

In this example, we are using the required_providers block to specify that we require at least version 3.0.0 of the AWS provider. By using the >= operator, we allow Terraform to use any version of the provider that is equal to or greater than 3.0.0, including the latest version.

Terraform will automatically download and use the latest version of the provider when we run terraform init. This command will also update or download other modules you might be using within the main one (or a root module). However, using a lot of modules that are using other modules is discouraged as it can cause dependency conflicts (for example, some old modules might require AWS provider version 1.23 when a root module requires version 3.0 or newer). We will get back to the CLI later in this chapter in the Terraform CLI subsection.

To refer to another module, you can use the module code block. Let’s say we have a simple module in the ./module/aws_ec2 directory relative to the root module. The aws_ec2 module expects to be fed with the ami, subnet, vpc, and security_group variables:

module "aws_ec2_instance" {
source = "./modules/aws_ec2"
ami = "ami-06dd92ecc74fdfb36"
subnet_id = "subnet-12345678"
vpc_id = "vpc-12345678"
security_group = "sg-12345678"
}

If a module exposes some outputs (variables you can use as input for a resource or other module), you can refer to them with module.NAME.OUTPUT_NAME. In this case, we could expose the ID of the EC2 instance, so you could refer to it with the name module.aws_ec2_instance.instance_id.

There are several other ways to specify the source argument when referring to a module in Terraform than using a local path:

  • The module can be stored and retrieved from a Git repository:
    module "example" {
    source = "git::https://github.com/example-org/example-module.git"
    }
    With a Git repository, you’re also able to refer to a commit ID, branch, or tag:
    module "example" {
    source = "git::https://github.com/example-org/example-module.git?ref=branch_name"
    }
    For the private repository, you will want to use SSH instead of HTTPS to clone it locally:
    module "example" {
    source = "git::ssh://github.com/example-org/example-module.git?ref=branch_name"
    }
  • The module can be published and retrieved from Terraform Registry:
    module "example" {
    source = "hashicorp/example-module/aws"
    }
    In this case, you can specify a module version with the version property, like so:
    module "example" {
    source = "hashicorp/example-module/aws"
    version = "1.0.0"
    }
  • The module can be stored and retrieved from an
    module "example" {
    source = "s3::https://s3-eu-cental-1.amazonaws.com/example-bucket/example-module.zip"
    }

You can find other possible sources in the official documentation: https://developer.hashicorp.com/terraform/language/modules/sources.

One of the essential concepts of Terraform is the state file. It is a JSON file that describes the current state of your infrastructure. This file is used to keep track of the resources that Terraform has created, updated, or deleted, and it also stores the configurations for each resource.

The purpose of the state file is to enable Terraform to manage your infrastructure consistently and reliably. By keeping track of the resources that Terraform has created or modified, the state file ensures that subsequent runs of Terraform will know the current state of your infrastructure and can make changes accordingly. Without the state file, Terraform would not know which resources are currently deployed and would be unable to make informed decisions about how to proceed with subsequent changes.

The state file is also used as a source of truth for Terraform’s plan and apply operations. When you run terraform plan or terraform apply, Terraform will compare the current state of your infrastructure with the desired state, as defined in your Terraform code. The state file is used to determine what changes need to be made to bring your infrastructure into the desired state. Overall, the state file is a crucial component of Terraform’s infrastructure management capabilities and enables Terraform to ensure the consistency and reliability of your infrastructure.

While the Terraform state file is a critical component of the tool, there are some downsides and challenges associated with using it.

The state file is a centralized file that is used to store information about your infrastructure. While this can be convenient, it can also create issues when working in a team setting, especially if multiple users are making changes to the same infrastructure concurrently. This can lead to conflicts and make it challenging to keep the state file up to date. It’s mitigated by the use of the distributed locking mechanism. In AWS environments, it’s simply a DynamoDB table with a lock entry with a state of 0 or 1.

Another downside of Terraform state is that the state file contains sensitive information about your infrastructure, such as passwords, keys, and IP addresses. Therefore, it’s essential to protect the state file from unauthorized access. If the state file is compromised, an attacker could potentially gain access to your infrastructure or sensitive data. Inside AWS, the state file is usually kept in an S3 bucket, which is necessary with enabled encryption and blocked public access.

The state file can become large and unwieldy over time, especially if you’re managing a large infrastructure with many resources. This can make it challenging to manage and maintain the state file, which can lead to errors and inconsistencies.

The next challenge we may encounter with state files is that Terraform state files are version-specific. This means that you must use the same version of Terraform to manage the state file as you did to create it. This can create issues when upgrading to a newer version of Terraform as you may need to migrate the state file to the new format.

Finally, Terraform’s state file has some limitations, such as the inability to manage external resources or the difficulty of handling complex dependencies between resources. This can create challenges when working with certain types of infrastructure or when dealing with complex deployments.

Another feature that comes with the state file is enforcing the configuration of the resources Terraform manages. If someone makes a manual change, you will see it on the next terraform plan or terraform apply and those changes will be rolled back.

With all that in mind, Terraform is still one of the best solutions out there and most of these challenges can easily be mitigated when planning our infrastructure.

Here’s an example backend.tf file that configures Terraform to use an S3 bucket named state-files for storing the state file and a DynamoDB table named terraform for state locking:

terraform {
backend "s3" {
bucket = "state-files"
key = "terraform.tfstate"
region = "eu-central-1"
dynamodb_table = "terraform"
}
}

In this configuration, the backend block specifies that we want to use the s3 backend type, which is designed to store the state file in an S3 bucket. The bucket parameter specifies the name of the bucket where the state file should be stored, and the key parameter specifies the name of the state file within the bucket.

The region parameter specifies the AWS region where the bucket is located. You should set this to the region that makes the most sense for your use case.

Finally, the dynamodb_table parameter specifies the name of the DynamoDB table that will be used for state locking. This is an important feature of the S3 backend as it ensures that only one user at a time can make changes to the infrastructure.

Here’s an example of the Terraform state file:

{
"version": 3,
"serial": 1,
"lineage": "f763e45d-ba6f-9951-3498-cf5927bc35c7",
"backend": {
"type": "s3",
"config": {
"access_key": null,
"acl": null,
"assume_role_policy": null,
"bucket": "terraform-states",
"dynamodb_endpoint": null,
"dynamodb_table": "terraform-state-lock",
"encrypt": true,
"endpoint": null,
"external_id": null,
"force_path_style": null,
"iam_endpoint": null,
"key": "staging/terraform.tfstate",
"kms_key_id": null,
"lock_table": null,
"max_retries": null,
"profile": null,
"region": "eu-central-1",
"role_arn": null,
"secret_key": null,
"session_name": null,
"shared_credentials_file": null,
"skip_credentials_validation": null,
"skip_get_ec2_platforms": null,
"skip_metadata_api_check": null,
"skip_region_validation": null,
"skip_requesting_account_id": null,
"sse_customer_key": null,
"sts_endpoint": null,
"token": null,
"workspace_key_prefix": null
},
"hash": 1619020936
},
"modules": [
{
"path": [
"root"
],
"outputs": {},
"resources": {},
"depends_on": []
}
]
}

By using the S3 backend with DynamoDB state locking, you can ensure that your Terraform deployments are safe and consistent, even in a team environment where multiple users may be making changes to the same infrastructure concurrently.

In the next subsection, we will discuss how to use the Terraform CLI and interact with our infrastructure and state files.

The core of Terraform is its command-line tool called, aptly, terraform. We linked the guide for installation when introducing Terraform to you. While there are tools to automate the workflow that remove the necessity of using the CLI, the use of the tool is simple and there is a lot of useful knowledge to be gained from working with it. In this section, we are going to introduce the most common options and workflows for the terraform command.

The very first subcommand of terraform you will use is terraform init. After you write your first portion of the main.tf file (if you follow the proposed module structure), you will run terraform init to download the required plugins and create some important directories and helper files.

Let’s consider a portion of the first piece of code we used previously:

terraform {
required_providers {
aws = {
source = "hashicorp/aws" version = "~> 4.0"
}
}
}

This code informs Terraform about the required plugin to be downloaded and its minimum version. Now, let’s run the terraform init command:

admin@myhome:~$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.58.0...
- Installed hashicorp/aws v4.58.0 (signed by HashiCorp)
Terraform has been successfully initialized!

We have shortened the output for brevity, but the most important part is there. You will see Terraform telling you what actions have been performed. The backend is the storage area for keeping the .tfstate file. If you don’t specify a storage area, the .tfstate file will be saved into terraform.tfstate in the local directory. There’s also a new subdirectory called .terraform where required plugins were installed. Finally, a .terraform.lock.hcl file exists, where Terraform records the versions of the providers that have been used so that you can keep them for compatibility reasons.

The terraform init command is a safe command. You can run it as many times as you wish; it won’t break anything.

The next command to run would be terraform fmt. This command formats your .tf files according to the best practices in place. Using it increases the readability and maintainability of your code, making all source files adhere to the same formatting strategy in all Terraform projects you will see. Running terraform fmt on our example will yield the following output:

admin@myhome:~$ terraform fmt
│ Error: Missing attribute separator
│
│ on main.tf line 4, in terraform:
│ 3: aws = {
│ 4: source = "hashicorp/aws" version = "~> 4.0"
│
│ Expected a newline or comma to mark the beginning of the next attribute.

You will notice that fmt caught a glaring error in my main.tf file. It is not only a readability issue; it may also introduce errors in code interpretation with some providers. I have put two attributes on one line. Editing it so that it looks like this fixes the issue:

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}

With this change, fmt is satisfied and we can proceed to the next step.

The plan of action is built by using the terraform plan command. It takes the last known recorded state of your infrastructure (terraform.tfstate), compares it to the code in the directory, and prepares steps to make them match. Running terraform plan with our preceding example code yields the following output:

admin@myhome:~$ terraform plan
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

Since we have not introduced any code that would create any resource, Terraform informed us that no changes are planned.

This, however, is not very interesting. Therefore, we are going to show you something that will create some resources in AWS.

Note

Before you follow this example, please consult your liability for the Free Tier services in AWS. Running these examples can incur a cost and neither the authors of this guide nor the publisher can claim any responsibility for them if they do occur.

If you want to follow these examples, you will need to have an AWS account (which is free at the time of writing this book). Then, you will need to create a role and generate AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Doing so is outside the scope of this chapter.

We have edited the preceding example slightly. The required_providers block has been moved to providers.tf. We have also added another provider block there. The file looks like this:

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-west-2"
}

Notice that the new block is configuring a new provider resource called aws. The name (aws) is actually up to us and could be anything. Remember to give meaningful names, ones that will help you understand the code later on. We have provided a bare minimum of configuration for this provider, which is specifying a region where our resource will be started.

We do the actual work in the newly created empty main.tf file:

resource "aws_instance" "vm_example" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "DevOpsGuideTerraformExample"
}

Here, we inform Terraform that we want to create a new resource of the aws_instance type. We are calling it vm_example. Next, we tell the tool to use a VM image (AMI) called ami-830c94e3. The instance’s type (how much RAM it is going to have, how many CPU cores, how big the system drive is, and more) is t2.micro. Finally, we add a tag that can help us identify and search for this instance.

Let’s call terraform plan and apply it:

admin@myhome:~$ 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.vm_example will be created
+ resource "aws_instance" "vm_example" {
+ ami = "ami-830c94e3"
[...]
+ tags = {
+ "Name" = "DevOpsGuideTerraformExample"
}
+ tags_all = {
+ "Name" = "DevOpsGuideTerraformExample"
}
+ tenancy = (known after apply)
[...]
+ vpc_security_group_ids = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
────────────────────────────────────────────────────────────────────

Note

You didn’t use the -out option to save this plan, so Terraform can’t guarantee to take exactly these actions if you run terraform apply now.

We’ve cut out a lot of the output from the plan. However, you can see that it differs from the previous example. Terraform noticed that we don’t have a VM with the specified parameters (remember, it compares to the .tfstate file). So, it is going to create one. We can always see the summary on the line starting with Plan. In the plan, all attributes starting with + (plus sign) will be created. Everything starting with - (minus sign) will be destroyed and everything with ~ (tilde) in front of it will be modified.

Be cautious with Terraform when changing attributes of already created resources. More often than not, it will treat it as something new, especially if you change names. This will result in destroying the VM with the old name and creating a new one with a new name. This is probably not what you want.

The plan is being implemented by calling terraform apply. This command will introduce changes to your environment if your .tf files differ from your .tfstate file. Also, if your actual running infrastructure differs from your .tfstate file, terraform apply will do its best to re-align the live infrastructure with the Terraform state file:

admin@myhome:~$ terraform apply
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.vm_example will be created
+ resource "aws_instance" "vm_example" {
+ ami = "ami-830c94e3"
[...]
+ subnet_id = (known after apply)
+ tags = {
+ "Name" = "DevOpsGuideTerraformExample"
}
+ tags_all = {
+ "Name" = "DevOpsGuideTerraformExample"
}
+ tenancy = (known after apply)
[...]
+ vpc_security_group_ids = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_instance.vm_example: Creating...
aws_instance.vm_example: Still creating... [10s elapsed]
aws_instance.vm_example: Still creating... [20s elapsed]
aws_instance.vm_example: Still creating... [30s elapsed]
aws_instance.vm_example: Still creating... [40s elapsed]
[...]
aws_instance.vm_example: Still creating... [1m20s elapsed]
aws_instance.vm_example: Creation complete after 1m29s [id=i-0a8bee7070b7129e5]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Again, a lot of the output has been cut out for brevity.

The terraform apply command created a plan again. We can avoid this by recording terraform plan into a file and later feeding the file to the apply step.

The interesting part is the confirmation step, where Terraform asks you to type in yes before it proceeds. Then, it is going to print out a summary of performed actions every 10 seconds. After you’ve spent some time working with Terraform, you will usually guess whether the action was successful by the time it takes it to finish.

In the AWS console, in the Instances menu, we can observe that the VM has been created:

Figure 12.1 – New VM instances created via Terraform

We can delete all the infrastructure we have just created by running terraform destroy.

An interesting thing to note is that at no point in our workflow have we told Terraform what files it should interpret. This is because, as mentioned previously, it will read all .tf files in the current directory and create a proper plan of execution.

If you are interested in seeing the hierarchy of steps, Terraform provides the terraform graph command, which will print it out for you:

admin@myhome:~$ terraform graph
digraph {
compound = "true"
newrank = "true"
subgraph "root" {
"[root] aws_instance.vm_example (expand)" [label = "aws_instance.vm_example", shape = "box"]
"[root] provider[\"registry.terraform.io/hashicorp/aws\"]" [label = "provider[\"registry.terraform.io/hashicorp/aws\"]", shape = "diamond"]
"[root] aws_instance.vm_example (expand)" -> "[root] provider[\"registry.terraform.io/hashicorp/aws\"]"
"[root] provider[\"registry.terraform.io/hashicorp/aws\"] (close)" -> "[root] aws_instance.vm_example (expand)"
"[root] root" -> "[root] provider[\"registry.terraform.io/hashicorp/aws\"] (close)"
}
}

There are tools out there that can create a nice visual representation of the graph produced by Terraform.

Occasionally, there’s a need to modify the resources in the state file. In the older versions of Terraform, this had to be done manually and was error-prone. Thankfully, Terraform developers added some CLI commands that could help us with that.

The most useful commands are as follows:

  • Terraform state rm: This command removes the resource from the state. This is useful when we’ve removed the resource manually and from the Terraform code but it persists in the state.
  • terraform state mv: This command changes the name of the resource. This is useful when we change the resource name to prevent the removal and creation of a new resource, which often isn’t the desired behavior
  • terraform taint: This command forces the resource to be recreated.

Importing existing resources into Terraform allows you to include those resources in your Terraform state, which is a snapshot of the resources managed by Terraform.

The terraform import command is used to add an existing resource to your Terraform state. This command maps the existing resource to a configuration block in your Terraform code, which allows you to manage the resource using Terraform.

The syntax for the terraform import command is as follows:

terraform import [options] resource_in_code resource_identifier

The two important arguments for the terraform import command are as follows:

  • resource_in_code: The address of the resource in your Terraform code
  • resource_identifier: The unique identifier of the resource you want to import

For example, let’s say you have an existing AWS S3 bucket with an Amazon Resource Names (ARN) of arn:aws:s3:::devopsy-bucket. To import this resource into your Terraform state, you can run the following command:

terraform import aws_s3_bucket.devopsy_bucket arn:aws:s3:::devopsy-bucket

Importing resources is useful when you have pre-existing infrastructure that you want to manage using Terraform. This is often the case when you are starting to use Terraform on an existing project or when you have resources that were created outside of Terraform. Importing resources allows you to bring those resources under Terraform management, so you can use Terraform to make changes to them in the future.

Not all resources can be imported into Terraform. The resource you intend to import must have a unique identifier that Terraform can use to locate it in the remote service. Additionally, the resource must be supported by the provider you are using in Terraform.

Terraform has a notion of a workspace. A workspace is similar to the version of the state. Workspaces allow you to store different states for the same code. To be able to use workspaces, you have to store your state file in a backend that supports them. The list of backends that support workspaces is quite long and covers the most popular cloud providers.

These workspaces are available in .tf files via the ${terraform.workspace} sequence. Along with conditional expressions, this allows you to create varying environments. For example, you can use different IP addresses, depending on the workspace, allowing you to specify testing and production environments.

There is always one workspace present: default. It can’t be removed. Workspace manipulation can be done using the terraform workspace command.

We can easily inspect what workspaces we have and which one is active using the terraform list command:

admin@myhome:~$ terraform workspace list
* default

The one with an asterisk in front of it is the current one. If we’re only interested in seeing the current workspace and not the whole list, we can run the terraform show command:

admin@myhome:~$ terraform workspace show
default

Each workspace will have a state file. Let’s experiment: we will create a new workspace called testing and apply Terraform to the testing workspace.

First, we must call terraform workspace new to create the workspace:

admin@myhome:~$ terraform workspace new testing
Created and switched to workspace "testing"!
You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.

Now, we must confirm that we are actually in the new workspace and run terraform apply in it using our previous example:

admin@myhome:~$ terraform apply
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.vm_example will be created
+ resource "aws_instance" "vm_example" {
+ ami = "ami-830c94e3"
[...]
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_instance.vm_example: Creating...
aws_instance.vm_example: Still creating... [10s elapsed]
aws_instance.vm_example: Still creating... [20s elapsed]
aws_instance.vm_example: Still creating... [30s elapsed]
aws_instance.vm_example: Still creating... [40s elapsed]
aws_instance.vm_example: Still creating... [50s elapsed]
aws_instance.vm_example: Creation complete after 57s [id=i-06cf29fde369218e2]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

As you can see, we successfully created the VM. However, when we change the workspace back to the default one, suddenly, Terraform will want to create it again:

admin@myhome:~$ terraform workspace switch default
Switched to workspace "default".
admin@myhome:~$ terraform apply
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.vm_example will be created
+ resource "aws_instance" "vm_example" {
[...]

Even though the creation of the resource was successful, Terraform will want to create it anew. When we inspect the directory where our .tf files live, we will spot the .tfstate file that is connected to the default workspace and a new directory called terraform.tfstate.d/ where .tfstate files are stored, each in its own subdirectory named aptly after the workspace. So, for the testing workspace, the state file will be stored in terraform.tfstate.d/testing:

admin@myhome:~$ ll
total 40
-rw-r--r-- 1 trochej staff 159B Mar 21 13:11 main.tf
-rw-r--r-- 1 trochej staff 158B Mar 21 12:27 providers.tf
-rw-r--r-- 1 trochej staff 4.4K Mar 21 21:17 terraform.tfstate
-rw-r--r-- 1 trochej staff 180B Mar 21 21:15 terraform.tfstate.backup
drwxr-xr-x 3 trochej staff 96B Mar 21 21:07 terraform.tfstate.d
admin@myhome:~$ ll terraform.tfstate.d
total 0
drwxr-xr-x 3 trochej staff 96B Mar 21 21:20 testing
admin@myhome:~$ ll terraform.tfstate.d/testing
total 8
-rw-r--r-- 1 trochej staff 180B Mar 21 21:18 terraform.tfstate

How can we use this to our advantage in Terraform code? As we have mentioned, there’s a special sequence (let’s call it a variable) that will be expanded to the name of the current workspace in our code:

resource "aws_instance" "vm_example" {
ami = "ami-830c94e3"
instance_type = terraform.workspace == "default" ? "t2.micro" : "t2.nano"
tags = {
Name = "DevOpsGuideTerraformExample"
}

With this small change (if terraform.workspace is the default, then the instance will be t2.micro; otherwise, it will be t2.nano) we have introduced a conditional change related to the workspace we start the VM in.

Let’s quickly confirm this with terraform plan:

admin@myhome:~$ terraform workspace show
default
admin@myhome:~$ terraform plan | grep instance_type
+ instance_type = "t2.micro"
admin@myhome:~$ terraform workspace select testing
Switched to workspace "testing".
admin@myhome:~$ terraform plan | grep instance_type
+ instance_type = "t2.nano"

As shown in the preceding output, depending on the workspace we select, different types of an instance will be created.

In this section, we dived deep into the Terraform IaC tool. We explained what providers and modules are, as well as the role of the state file. We also demonstrated simple Terraform configuration and its interaction with the AWS cloud.

In the next section, we are going to cover the HashiCorp Configuration Language (HCL) in more detail, which was created specifically to write those configurations.

HCL is a configuration language that’s used by several HashiCorp tools, including Terraform, to define and manage IaC.

HCL is designed to be easy to read and write for both humans and machines. It uses a simple syntax that is similar to JSON but with a more relaxed structure and support for comments. HCL files typically have an .hcl or .tf file extension.

HCL uses curly braces to define blocks of code, and each block has a label that identifies its type. Within each block, we define attributes using a key-value syntax, where the key is the attribute name and the value is the attribute value. We can also define objects using curly braces, as shown in the example with the tags object.

In HCL, variables are defined using the variable block. Here’s an example of how to define a variable in HCL:

variable "region" {
type = string
default = "eu-central-1"
}

In this example, we define a variable named region of the string type and a default value of us-west-2. We can reference this variable later in our code using the ${ var.region} syntax.

HCL supports several data types for variables, including string, number, boolean, list, map, and object. We can also specify a description for the variable using the description argument in the variable block.

Variables can be assigned values in a variety of ways, including through default values, command-line arguments, or environment variables. When using Terraform, we can also define variables in a separate file and pass them in during execution using a .tfvars file extension (for example, variables.tfvars) or through command-line arguments.

Once variables have been defined, they can’t be changed, but HCL also allows local variables that can be defined within the locals block. Local variables are useful for simplifying complex expressions or calculations within a module or resource block as they allow us to break down the logic into smaller, more manageable pieces. They can also make it easier to maintain our code as we can define local variables for values that may change frequently or need to be updated across multiple resources or modules.

Here’s an example locals block that defines the availability zones (AZ) in the eu-central-1 region and generates subnets in every AZ:

locals {
azs = ["eu-central-1a", "eu-central-1b", "eu-central-1c"]
cidr_block = "10.0.0.0/16"
subnet_bits = 8
subnets = {
for idx, az in local.azs : az => {
name = "${var.environment}-subnet-${idx}"
cidr_block = cidrsubnet(local.cidr_block, local.subnet_bits, idx)
availability_zone = az
}
}
}

In this example, we define a locals block that includes the following variables:

  • azs: A list of the availability zones in the eu-central-1 region
  • cidr_block: The CIDR block for the VPC
  • subnet_bits: The number of bits to allocate for subnets within the CIDR block
  • subnets: A map that generates subnets for each availability zone in the azs list using a for expression

The for expression in the subnets map generates a subnet for each availability zone in the azs list. The subnet’s name includes the environment variable (which can be passed in as a variable) and the index of the availability zone in the list. The cidrsubnet function is used to calculate the CIDR block for each subnet based on the cidr_block variable and the subnet_bits variable.

The resulting subnets map will contain a key-value pair for each availability zone in the azs list, where the key is the availability zone name and the value is a map that includes the subnet name, CIDR block, and availability zone.

Comments in HCL can be written in two ways: single-line and multi-line comments. Single-line comments begin with the # symbol and continue until the end of the line. Multi-line comments, on the other hand, start with /* and end with */. Multi-line comments can span multiple lines and are often used to provide longer explanations or temporarily disable sections of code.

The following is an example of a single-line comment:

# This is a single-line comment in HCL

The following is an example of a multi-line comment:

/*
This is a multi-line comment in HCL
It can span multiple lines and is often used
to provide longer explanations or to temporarily disable sections of code.
*/

In Terraform, meta-arguments are special arguments that can be used to modify the behavior of resource blocks. They are called meta-arguments because they apply to the resource block as a whole, rather than to specific attributes within the block.

Meta-arguments are used to configure things such as the number of instances of a resource to create (count), the names of resources (name), the dependencies between resources (depends_on), and more.

count allows you to create multiple instances of a resource based on a numeric value. This can be useful for creating multiple instances of a resource, such as EC2 instances in AWS, without having to repeat the entire block of code.

For example, let’s say you want to create three EC2 instances in your AWS account. Instead of creating three separate aws_ec2_instance resource blocks, you can use the count meta-argument to create multiple instances of the same block. Here’s an example:

resource "aws_ec2_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
count = 3
}

In this example, we’re creating three EC2 instances using the same ami and instance_type. The count meta-argument is set to 3, which means that Terraform will create 3 instances of the aws_ec2_instance resource block. Each instance will be given a unique identifier, such as aws_ec2_instance.example[0], aws_ec2_instance.example[1], and aws_ec2_instance.example[2].

The for_each meta-argument is similar to the count meta-argument in that it allows you to create multiple instances of a resource. However, for_each is more flexible than count because it allows you to create instances based on a map or set of values, rather than just a numeric value.

For example, let’s say you have a map of AWS security groups that you want to create in your Terraform code. Instead of creating multiple aws_security_group resource blocks, you can use for_each to create them all in a single block. Here’s an example:

variable "security_groups" {
type = map(object({
name = string
description = string
ingress = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
}))
}
resource "aws_security_group" "example" {
for_each = var.security_groups
name_prefix = each.value.name
description = each.value.description
ingress {
from_port = each.value.ingress[0].from_port
to_port = each.value.ingress[0].to_port
protocol = each.value.ingress[0].protocol
cidr_blocks = each.value.ingress[0].cidr_blocks
}
}

In this example, we’re using the for_each meta-argument to create multiple instances of the aws_security_group resource block based on the security_groups variable, which is a map of objects. Each instance will have a unique identifier based on the key of the map. We’re also using the name_prefix attribute to set the name of each security group, and the description attribute to set the description. Finally, we’re using the ingress block to define the inbound traffic rules for each security group.

Using for_each can simplify your Terraform code and make it more reusable, especially when you’re dealing with maps or sets of values. However, it’s important to be aware of any potential dependencies between instances and to make sure that your code is properly structured to handle multiple instances.

The lifecycle meta-argument is used to define custom behavior for creating, updating, and deleting resources. It allows you to control the life cycle of a resource and its dependencies in a more fine-grained manner than the default behavior.

The lifecycle meta-argument can be used to define the following attributes:

  • create_before_destroy: If set to true, Terraform will create the new resource before destroying the old one, which can prevent downtime in some cases.
  • prevent_destroy: If set to true, Terraform will prevent the resource from being destroyed. This can be useful for protecting critical resources from accidental deletion.
  • ignore_changes: A list of attribute names that Terraform should ignore when determining whether a resource needs to be updated.
  • replace_triggered_by: A list of dependencies that will cause the resource to be recreated.

Here’s an example of using the lifecycle meta-argument to prevent the destruction of an S3 bucket:

resource "aws_s3_bucket" "example" {
bucket = "example-bucket"
acl = "private"
lifecycle {
prevent_destroy = true
}
}

In this example, the lifecycle block is used to set the prevent_destroy attribute to true, which means that Terraform will prevent the aws_s3_bucket resource from being destroyed. This can be useful for protecting critical resources from being accidentally deleted.

The depends_on meta-argument is used to define dependencies between resources. It allows you to specify that one resource depends on another resource, which means that Terraform will create the dependent resource after the resource it depends on has been created.

However, it’s important to note that in most cases, Terraform can create a dependency tree automatically by analyzing your resource configurations. This means that using depends_on should be avoided unless absolutely necessary as it can lead to dependency cycles that can cause errors and make your Terraform code harder to manage.

If you do need to use depends_on, it’s important to be aware of the potential for dependency cycles and to structure your code in a way that avoids them. This might involve splitting your resources into smaller modules or using other techniques to reduce complexity and avoid circular dependencies.

Here’s an example of using depends_on to specify a dependency between an EC2 instance and a security group:

resource "aws_security_group" "example" {
name_prefix = "example"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
depends_on = [aws_security_group.example]
}

In this example, we’re using depends_on to specify that the aws_instance resource depends on the aws_security_group resource. This means that Terraform will create the security group before creating the instance.

You can find out more about the HCL language by reading the official documentation: https://developer.hashicorp.com/terraform/language.

In this section, we will create two sample modules to demonstrate how you would go about creating one and what you will need to consider when choosing the way it is supposed to create resources. The module we are going to create will be able to create one or more EC2 instances, a security group attached to it, and other needed resources, such as an instance profile. It will do almost everything we went through in Chapter 10, but with the use of the AWS CLI.

Let’s create a module that will be able to create EC2 instances. Consider the following directory structure:

├── aws
│ └── eu-central-1
└── modules

The modules directory is where we will put all our modules, aws is where we will keep our AWS infrastructure, and eu-central-1 is the code of the infrastructure for the Frankfurt AWS region. So, let’s go ahead and start with creating the EC2 module. Let’s create a directory to hold it and the basic files we will need, as we described earlier:

admin@myhome:~$ cd modules
admin@myhome:~/modules$ mkdir aws_ec2
admin@myhome:~/modules$ cd aws_ec2
admin@myhome:~/modules/aws_ec2$ touch versions.tf main.tf variables.tf outputs.tf providers.tf
admin@myhome:~/modules/aws_ec2$ ls -l
total 0
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 main.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 outputs.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 providers.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 variables.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 versions.tf
admin@myhome:~/modules/aws_ec2$

Notice that we didn’t create the backend configuration file. This is because the backend will be configured in the root module instead. Modules don’t have state files as the resources created by the module will be using the state file from the root (or in other words, main) module. Let’s start configuring providers. In this case, we will only need the AWS provider at this moment. In our example, we will use the eu-central-1 region:

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

Next, let’s configure the versions of Terraform and the AWS provider we will use in the versions.tf file:

terraform {
required_version = ">= 1.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 3.0.0"
}
}
}

In this example, the required_version attribute is set to >= 1.0.0 to require Terraform version 1.0.0 or greater. The required_providers attribute is used to specify the AWS provider, with the source attribute set to hashicorp/aws and the version attribute set to >= 3.0.0 to require the latest version of the AWS provider.

Now, we can do more interesting things, such as adding an actual aws_instance resource. For that, we will start filling the variables this resource needs:

resource "aws_instance" "test_instance" {
ami = "ami-1234567890"
instance_type = "t3.micro"
tags = {
Name = "TestInstance"
}
}

After saving all changes to the module files, we can go back to the aws/eu-central-1 directory and create a similar set of files as in the module:

admin@myhome:~/modules/aws_ec2$ cd ../../aws/eu-central-1
admin@myhome:~/aws/eu-central-1$ touch versions.tf main.tf variables.tf providers.tf
admin@myhome:~/aws/eu-central-1$ ls -l
total 0
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 main.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 providers.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 variables.tf
-rw-r--r-- 1 admin admin 0 Mar 16 13:02 versions.tf
admin@myhome:~/aws/eu-central-1$

This time, we will only need main.ft, providers.tf, variables.tf, and versions.tf. To simplify things, we can just copy the contents of the providers and the versions files:

admin@myhome:~/aws/eu-central-1$ cp ../../modules/aws_ec2/providers.tf .
admin@myhome:~/aws/eu-central-1$ cp ../../modules/aws_ec2/versions.tf .

Now, we can focus on the main.tf file, where we’re going to try and use our first version of the module. The main.tf file will look like this:

module "test_instance" {
source = "../../modules/aws_ec2"
}

The module we’ve created doesn’t require any variables, so this is all we need in this file.

Since this is our root module, we will also need to configure the location of the Terraform state file. For simplicity, we will use a local state file, but in real life, we recommend using an S3 bucket with a distributed lock configured. If there is no backend block, Terraform will create a local file. We’re ready to test our module (the output has been shortened for brevity):

admin@myhome:~/aws/eu-central-1$ terraform init
Initializing modules...
- test_instance in ../../modules/aws_ec2
Initializing the backend...
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Once you’ve run terraform init (you only have to rerun it if you update modules or backend configuration), you can execute terraform plan to see what changes have to be applied:

admin@myhome:~/aws/eu-central-1$ 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:
# module.test_instance.aws_instance.test_instance will be created
+ resource "aws_instance" "test_instance" {
+ ami = "ami-1234567890"
# Some of the output removed for readability
Plan: 1 to add, 0 to change, 0 to destroy.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note

You didn’t use the -out option to save this plan, so Terraform can’t guarantee it will take exactly these actions if you run terraform apply now.

With this plan, Terraform confirmed that our module will create an EC2 instance for us. Unfortunately, this plan is not ideal as it doesn’t check whether the AMI actually exists, or whether the subnet is there. Those errors will come up when we run terraform apply. The AMI we’ve provided, for instance, is bogus, so Terraform will fail in creating the instance. Let’s get back to the module and improve it by automatically getting a correct Ubuntu Linux AMI. For this, the Terraform AWS provider provides a data resource. This special resource enables us to ask AWS for various resources through their API. Let’s add an AMI data resource to the modules directory’s main.tf file:

data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
resource "aws_instance" "test_instance" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
tags = {
Name = "TestInstance"
}
}

The (aws_ami) block of code uses the aws_ami data source to fetch the latest Ubuntu AMI owned by Canonical from the AWS Marketplace. It does this by setting the most_recent parameter to true and filtering the results using the name attribute of the AMI. It looks for an AMI with a specific name pattern: ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*.

The second block of code creates an AWS EC2 instance using the AMI that was fetched in the first block of code. It sets the instance type to t3.micro, which is a small instance type that’s suitable for testing purposes.

It also adds a tag to the EC2 instance with a key called Name and a value called TestInstance so that it can easily be identified in the AWS Management Console.

You can read more about the aws_ami data resource in the documentation: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami.

After making this modification, we can run terraform plan and see whether something changes:

admin@myhome:~/aws/eu-central-1$ 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:
# module.test_instance.aws_instance.test_instance will be created
+ resource "aws_instance" "test_instance" {
+ ami = "ami-050096f31d010b533"
# Rest of the output removed for readability

The plan succeeded and it seems it found a recent AMI for Ubuntu Linux 22.04. There are a few other issues we’ll need to consider if we want to make sure we’ll be able to connect to this new EC2 instance. Of course, it will be created if we apply the changes, but we don’t have a way to connect to it. First, let’s connect the EC2 instance to the correct network: we will use a default VPC and a public subnet, which will allow us to connect to this instance directly.

To figure out the ID of the default VPC and a public subnet, once again, we will use a data resource:

The question is whether we want to automatically put all created instances in a default VPC (and a public subnet) or not. Usually, the answer to this question is no. In that case, we will need to add some variables to be passed to this module.

Let’s add another file to the root module, in which we will put all the data resources, called data.tf:

data "aws_vpc" "default" {
filter {
name = "isDefault"
values = ["true"]
}
}
data "aws_subnets" "public" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
filter {
name = "map-public-ip-on-launch"
values = ["true"]
}
}

Now, we can create an input variable in our module. Go back to the modules/aws_ec2 directory and edit the variables.tf file:

variable "public_subnet_id" {
description = "Subnet ID we will run our EC2 instance"
type = string
}

Now, when you run terraform plan, you will see the following error:

│ Error: Missing required argument
│
│ on main.tf line 1, in module "test_instance":
│ 1: module "test_instance" {
│
│ The argument "public_subnet_id" is required, but no definition was found.

Here, we’ve created a mandatory variable we will need to provide to the module. Let’s do so by editing the main.tf file in our root module (the aws/eu-central-1 directory):

module "test_instance" {
source = "../../modules/aws_ec2"
public_subnet_id = data.aws_subnets.public.ids[0]
}

Notice data.aws_subnets.public.ids[0]. We’ve used a list notation, where we’re choosing the first element of the list (which is a string since the module expects it to be). This is because there are multiple subnets and aws_subnets returned a list of those subnets for us.

Running a plan again should give us one resource to be added. Great! Now, our instance will get a public IP address we can connect to. But we’re still missing a firewall rule that will allow us to connect to port 22 (SSH). Let’s create a security group (SG).

Again, we could decide to create an SG in the root module, which would allow us to modify it without changing the EC2 module. Alternatively, we could add an SG inside the EC2 module, which would mean that the module would have full control over it, but it would lack some flexibility. It’s also possible to create a module that would do both: attach an SG injected from the root module and, at the same time, use an SG predefined in the module, but this is outside the scope of this chapter. In this case, we’re going to create an SG inside the module for simplicity’s sake.

To create an SG, we will use the aws_security_group resource, which requires a VPC ID. There are two possibilities: we will need to introduce another variable to our EC2 module, or we will use another data resource to automatically get the VPC ID from the provided subnet. This time, a more elegant solution would be to use data resources. Let’s add it to main.tf in our module:

data "aws_subnet" "current" {
id = var.public_subnet_id
}

With that in place, we will be able to add an SG now:

resource "aws_security_group" "allow_ssh" {
name = "TestInstanceSG"
description = "Allow SSH traffic"
vpc_id = data.aws_subnet.current.vpc_id
ingress {
description = "SSH from the Internet"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "TestInstanceSG"
}
}

The preceding code creates an AWS SG that allows SSH traffic to the EC2 instance we created earlier.

The aws_security_group resource is used to create an SG for the EC2 instance. It sets the name of the SG to TestInstanceSG and provides a brief description.

The vpc_id attribute is set to the VPC ID of the current subnet. It uses the aws_subnet data source called current to fetch the current subnet’s VPC ID.

The ingress block defines the inbound rules for the security group. In this case, it allows SSH traffic from any IP address (0.0.0.0/0) by specifying from_port, to_port, protocol, and cidr_blocks.

The egress block defines the outbound rules for the security group. In this case, it allows all outbound traffic by specifying from_port, to_port, protocol, and cidr_blocks. It also allows all IPv6 traffic by specifying ipv6_cidr_blocks.

The tags attribute sets a tag for the SG with a key called Name and a value called TestInstanceSG so that it can be easily identified in the AWS Management Console.

Now, we’re ready to attach this SG to our instance. We will need to use the security_groups option for the aws_instance resource:

resource "aws_instance" "test_instance" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
security_groups = [aws_security_group.allow_ssh.id]
tags = {
Name = "TestInstance"
}
}

Now, after running terraform plan, you will see two resources to be added:

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

At this point, we need to add our public SSH key to AWS and configure EC2 to use it for a default Ubuntu Linux user (ubuntu). Assuming you have already generated your SSH key, we will create a variable with said key, create a resource that will make the key available for the EC2 instance, and finally, add it to the instance configuration.

Important note

In some AWS regions, it’s required to use an old RSA key format. Whenever available, we recommend the newest format according to up-to-date recommendations. At the time of writing this book, it’s recommended to use the ED25519 key.

Let’s add a variable to the root module:

variable "ssh_key" {
description = "SSH key attached to the instance"
type = string
default = "ssh-rsa AAASomeRSAKEY""
}

Let’s add a similar one for the EC2 module:

variable "ssh_key" {
description = "SSH key attached to the instance"
type = string
}

This one is without the default value to make this variable required for every module in use. Now, let’s add the key to AWS inside the EC2 module (main.tf):

resource "aws_key_pair" "deployer" {
key_name = "ssh_deployer_key"
public_key = var.ssh_key
}

Then, we can use it in the aws_instance resource:

resource "aws_instance" "test_instance" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
security_groups = [aws_security_group.allow_ssh.id]
key_name = aws_key_pair.deployer.key_name
tags = {
Name = "TestInstance"
}
}

We will need to use the new variable inside the root module in main.tf:

module "test_instance" {
source = "../../modules/aws_ec2"
public_subnet_id = data.aws_subnets.public.ids[0]
ssh_key = var.ssh_key
}

Finally, running terraform plan will give us three resources:

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

Great! Running terraform apply and accepting any changes will deploy the EC2 instance in a public subnet with our key. However, we still won’t know the IP address for the instance unless we go to the AWS console and check it manually.

To get this information, we will need to export these variables from the EC2 module and then once again in the root module. For this, we have another code block called output. Its syntax is very similar to the variable syntax, but additionally, you can mark the output variable as sensitive so that it’s not shown by default when running terraform plan or terraform apply commands.

Let’s define outputs showing us the public IP address of the EC2 instance. In the EC2 module in the outputs.tf file, place the following code:

output "instance_public_ip" {
value = aws_instance.test_instance.public_ip
description = "Public IP address of the EC2 instance"
}

In the root module, create the outputs.tf file and put the following code there:

output "instance_public_ip" {
value = module.test_instance.instance_public_ip
description = "Public IP address of the instance"
}

Now, when you run terraform plan, you will see a change in the output:

Plan: 3 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ instance_public_ip = (known after apply)

This way, we’ve created a simple module by creating a single EC2 instance. If we run terraform apply, the instance will be created and the output will show us the IP address.

From here, the next steps would involve adding more functionality to the module, adding the ability to create more than one instance with the count meta-argument, or creating a set of different EC2 instances by using the for_each meta-argument.

In this chapter, we introduced the concept of IaC. We explained why it is an important method of managing and developing your infrastructure. We also introduced some tools that are quite popular in this way of working. As a tool of choice, we explained Terraform – probably the most widely used one.

In the next chapter, we are going to show you how you can leverage some online tools and automation to build pipelines for CI and CD.

Try out the following exercises to test what you’ve learned in this chapter:

  1. Create a module that will create an S3 bucket with enabled server-side encryption.
  2. Add an instance profile to the module we’ve created using the same IAM policy that we used in Chapter 10.
  3. Use the count meta-argument to create two instances.