Introduction to Terraform

Introduction to Terraform

Day 1 of #TerraWeek

I am delighted to announce that I have accepted to participate in the TWS TerraWeek Challenge created by Shubham Londhe! This will be a great journey on the Infrastructure as a Code(IaC).

Over these next 7 days, I will put my basic knowledge to the test. Whether you're an expert or just a fresher(like me) on Terraform, this challenge will offer everyone achieve some basic knowledge of it. I will use this blog for sharing some posts, about the basics of IaC and the most used tool for this, Terraform.

📝Infrastructure as a Code(IaC)

Infrastructure as Code (IaC) is the managing and provisioning of infrastructure through code instead of through manual processes.

Using the IaC, configuration files are created that contain your infrastructure specifications, which makes it easier to edit and distribute configurations. It also ensures that you provide the same environment every time.

Another important part of IaC is version control, where our config files should be under source control like GitHub. Deploying our infrastructure as code also means that you can divide your infrastructure into modular components that can then be combined in different ways through automation.

Automating infrastructure provisioning with IaC means that developers don’t need to manually provision and manage servers, operating systems, storage, and other infrastructure components each time they develop or deploy an application.

📝Declarative vs. Imperative approaches to IaC

There are 2 ways to approach IaC: declarative or imperative.

A Declarative approach defines the desired state of the system, including what resources you need and any properties they should have, and an IaC tool will configure it for you.

It also keeps a list of the current state of your system objects, which makes taking down the infrastructure simpler to manage.

On the other hand, the Imperative approach instead defines the specific commands needed to achieve the desired configuration, and those commands then need to be executed in the correct order. 

Many IaC tools use a Declarative approach and will automatically provision the desired infrastructure, Terraform uses it. However, if you make changes to the desired state, a Declarative IaC tool will apply those changes for you. Although in Imperative tool will require you to figure out how those changes should be applied, for example, AWS CLI uses it.

IaC tools are often able to operate in both approaches but tend to prefer one approach over the other.

i.e. Declarative (Terraform)

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

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "us-west-2"
}

resource "aws_instance" "app_server" {
  ami           = "ami-830c94e3"
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

i.e. Imperative (AWS CLI)

aws s3api create-bucket --bucket my-first-website-cloud-native-website --region eu-central-1

📝Benefits of IaC

Provisioning infrastructure has historically been a time-consuming and costly manual process.

Now infrastructure management has moved away from physical hardware in data centres, though this still may be a component for your organization, to virtualization, containers, and cloud computing.

With cloud computing, the number of infrastructure components has grown, more applications are being released to production on a daily basis, and infrastructure needs to be able to be spun up, scaled, and taken down frequently.

Without an IaC practice in place, it becomes increasingly difficult to manage the scale of today’s infrastructure.

IaC can help our organizations manage IT infrastructure needs while also improving consistency and reducing errors and manual configuration.

Benefits:

  • Improve speed: Automation is faster than manually navigating an interface when you need to deploy and/or connect resources.

  • Improve reliability: If your infrastructure is large, it becomes easy to misconfigure a resource or provision services in the wrong order. With IaC, the resources are always provisioned and configured exactly as declared.

  • Prevent configuration drift: Configuration drift occurs when the configuration that provisioned your environment no longer matches the actual environment. (See ‘Immutable infrastructure’ below.)

  • Support experimentation, testing, and optimization: Because Infrastructure as Code makes provisioning new infrastructure so much faster and easier, you can make and test experimental changes without investing lots of time and resources; and if you like the results, you can quickly scale up the new infrastructure for production.

📝Why Terraform?

There are a few key reasons developers choose to use Terraform over other Infrastructures as Code(IaC) tools:

  • Open source: Terraform is backed by large communities of contributors who build plugins for the platform. Regardless of which cloud provider you use, it’s easy to find plugins, extensions, and professional support.

  • Platform agnostic: This means you can use it with any cloud services provider(Multicloud). Most other IaC tools are designed to work with a single cloud provider.

  • Immutable infrastructure: Most Infrastructure as Code tools create mutable infrastructure, meaning the infrastructure can change to accommodate changes such as a middleware upgrade or new storage server. The danger with mutable infrastructure is *configuration drift—*as the changes pile up, the actual provisioning of different servers or other infrastructure elements ‘drifts’ further from the original configuration, making bugs or performance issues difficult to diagnose and correct.

    Terraform provisions immutable infrastructure, which means that with each change to the environment, the current configuration is replaced with a new one that accounts for the change, and the infrastructure is reprovisioned. Even better, previous configurations can be retained as versions to enable rollbacks if necessary or desired.

    📝How does Terraform work?

    It creates and manages resources on cloud platforms and other services through its application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API.

    Terraform creates and manages cloud platforms and services through their APIs

We can find all publicly available providers on the Terraform Registry, including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more.

The core Terraform workflow consists of three stages:

  • Write: You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer.

  • Plan: Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration.

  • Apply: On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines.

The Terraform workflow has three steps: Write, Plan, and Apply

📝Terraform Core Concepts

  • Variables: Terraform has input and output variables, it is a key-value pair. Input variables are used as parameters to input values at run time to customize our deployments. Output variables are return values of a terraform module that can be used by other configurations.

  • Provider: Terraform users provision their infrastructure on the major cloud providers such as AWS, Azure, OCI, and others. A provider is a plugin that interacts with the various APIs required to create, update, and delete various resources.

  • Module: Any set of Terraform configuration files in a folder is a module. Every Terraform configuration has at least one module, known as its root module.

  • State: Terraform records information about what infrastructure is created in a Terraform state file. With the state file, Terraform is able to find the resources it created previously, supposed to manage and update them accordingly.

  • Resources: Cloud Providers provide various services in their offerings, they are referenced as Resources in Terraform. Terraform resources can be anything from compute instances, and virtual networks to higher-level components such as DNS records. Each resource has its own attributes to define that resource.

  • Data Source: The data source performs a read-only operation. It allows data to be fetched or computed from resources/entities that are not defined or managed by Terraform or the current Terraform configuration.

  • Plan: It is one of the stages in the Terraform lifecycle where it determines what needs to be created, updated, or destroyed to move from the real/current state of the infrastructure to the desired state.

  • Apply: It is one of the stages in the Terraform lifecycle where it applies the changes real/current state of the infrastructure in order to achieve the desired state.

📝Terraform Configuration Files

Configuration files are a set of files used to describe infrastructure in Terraform and have the file extensions .tf and .tf.json. Terraform uses a Declarative model for defining infrastructure. Configuration files let you write a configuration that declares your desired state. Configuration files are made up of resources with settings and values representing the desired state of your infrastructure.

A Terraform configuration is made up of one or more files in a directory, provider binaries, plan files, and state files once Terraform has run the configuration.

  • Configuration file (*.tf files): Here we declare the provider and resources to be deployed along with the type of resource and all resources specific settings

  • Variable declaration file (variables.tf or variables.tf.json): Here we declare the input variables required to provision resources

  • Variable definition files (terraform.tfvars): Here we assign values to the input variables

  • State file (terraform.tfstate): A state file is created once after Terraform is run. It stores state about our managed infrastructure

📝Setting Up Terraform and Creating Your First Configuration

To start with Terraform, follow the steps below:

  • Download and install Terraform.

  • Verify the installation, please, run terraform -v to verify that Terraform is installed correctly on your terminal or prompt. You should see the version number displayed.

  • Create a new directory for your Terraform project where you will store your Terraform configuration files.

  • Create a Terraform configuration file called main.tf. This file will contain your Terraform main configuration.

  • Define a provider and resource in your main.tf For example, to create a simple AWS EC2 instance, you might use the following code:

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

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "us-west-2"
}

resource "aws_instance" "app_server" {
  ami           = "ami-830c94e3"
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}
  • To initialize Terraform, run terraform init. All required provider plugins will be downloaded and set up the backend for storing your state file.

  • To apply your configuration, run terraform apply . It will create your IaC. Type yes and press Enter to confirm and proceed with it.

  • To verify your infrastructure, once Terraform has finished applying your configuration, go through your cloud provider's console and check your new infrastructure created on it.

Thank you for reading. I hope you were able to understand and learn something helpful from my blog.

Please follow me on Hashnode and on LinkedIn franciscojblsouza