Learn Terraform: Automate and Manage your Infrastructure easily

November 29, 2021
Share this post:
Learn Terraform: Automate and Manage your Infrastructure easily

Infrastructure as Code provides a convenient way to manage and automate deployments to cloud infrastructure. In this blog, learn how Terraform can be used to perform Infrastructure as Code.

Table of Contents:

    If you are planning to automate your cloud infrastructure then nothing could be better than Terraform. Terraform is the most widely used and popular automation (infrastructure as code) tool that allows you to build and manage infrastructure easily and efficiently.

    In this Terraform series, you are going to learn from the ground up what Terraform is and what you need to know to manage and build your infrastructure using Terraform.

    Prerequisites

    This article will be a step by step guide. If you would like to follow along, be sure to have the following in place:

    • An AWS account
    • Terraform - This tutorial will use Terraform v1.0.8 running on Ubuntu 18.04.5 LTS, but any operating system with Terraform should work.

    Introduction to Terraform

    Terraform is a tool for building, versioning, and updating the infrastructure. It is written in GO Language and the syntax language of configuration files is HCL i.e HashiCorp Configuration Language(much easier than YAML or JSON).

    Terraform has been in use for quite a while now. It is an amazing tool to build and change the infrastructure in a very effective and simpler way. It can be used with a variety of cloud providers such as Amazon AWS, Oracle, Microsoft Azure, Google Cloud, and many more. Let's learn more about it.

    Key Features of Terraform

    Terraform as a tool is a big game changer to manage cloud infrastructure because of the ease of writing code which is such that the same code can be easily made to work with various cloud providers. There are several other key features of Terraform which make this tool so popular and handy. Let's discuss a few of them now.

    • Infrastructure as a code: Terraform execution and configuration files are written in Infrastructure as a code language - a high-level language which is easy to understand.
    • Execution Plan: Terraform provides you in depth details about the deployment and resources it will create before deploying the actual code.
    • Resource Graph: Terraform makes the life of an administrator simple by providing a graphical view of the resources that are currently being provisioned or are already provisioned.

    Files and Directories in Terraform

    Terraform code consists of Terraform configuration files that follow a standard structure - an arrangement of files and directories that improves code readability. Lets checkout details about these files and folders.

    Terraform modules are top-level directories. A single module contains mainly five Terraform configuration files: main.tf, vars.tf, providers.tf, output.tf and terraform.tfvars which are written with .tf format or .tf.json or .tfvars format. These are known as root modules.

    The Root module can call other child modules from either local directories or Terraform Registry or from anywhere in the disk

    As you can see in the below image there are two child modules - AWS EC2 and AWS S3. Modules containing all the required configurations(main.tf, vars.tf, provider.tf, terraform.tfvars etc) are the ROOT modules for themselves but also acts as child module for the other ROOT module that contains both EC2 and AWS S3.

    Files and Directories in Terraform

    Now, let's dive into five configuration files that a root module requires.

    • main.tf → The main.tf file contains the main code that defines which resources you need to create or manage the infrastructure. Below is an example of a main.tf file that creates a resource - 'ec2 instance' under which you need to define:
      • The resource type that you need to create- "aws_instance".
      • Arguments containing the values- "ami" and "instance_type" of type string.
      • Timeout is an argument of type map containing "create" and "delete" values.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/fb8c47ee2b74a984921e024348fe6fa2.js</p>

    • vars.tf → The vars.tf contains all the variables that the configuration file (main.tf) references. Below is an example of a vars.tf file that contains variables of different types that you refer to in main.tf, such as:
      • "my_instances" of type string.
      • "ami" of type map.
      • "number" of type boolean.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/f62b400dc760c7b8a3fa9a4364c266d5.js</p>

    • terraform.tfvars → terraform.tfvars contains the values that terraform uses to replace the variables referred inside main.tf.
    • output.tf → Terraform output configuration provides the output of AWS resources such as arn or IP address after you execute the terraform apply command. Below is an example of output.tf file that provides the resource outputs such as AWS EC2 instance arn, and public IP address after executing the terraform apply command

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/71ce72316d47fc6d663246d7f8aa5823.js</p>

    • provider.tf → The provider.tf file is where you define the AWS provider so that Terraform can connect to the correct cloud api services. Terraform uses AWS Provider with proper credentials to connect with Amazon to manage, deploy, update dozens of AWS services.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/d407411d6a3d16dcc4b092c56cad6038.js</p>

    Syntax of Terraform

    Previously you learned about the theoretical aspects of what Terraform is and how it works. But before you actually write a Terraform configuration file to create a resource, it is important to know the syntax.

    With Terraform, you can simply create the resources using resource blocks or by creating a module (A module is a container for multiple resources that are used together). Let's checkout the syntax.

    The below code is a resource block in Terraform where:

    • resource_aws is of resource block type.
    • aws_vpc and main are block labels.
    • Identifier cidr_block is the argument name.
    • expression var.block is the argument’s value.

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/37b57f4d33fb25e3d96fdaf80656a1d5.js</p>

    The Below code is a module block in Terraform where:

    • 'source' is the value which provides the path to a local directory containing the module's configuration files, or a remote module source that Terraform should download and use.
    • 'version' provides the acceptable version numbers to avoid unexpected or unwanted changes.

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/c52cacfdff90cf98cea0f244d5161064.js</p>

    Terraform Formats ( .tf and .tf.json)

    Terraform's code configuration files are stored in plain text as .tf format or in JSON based formats as .tf.json.

    Lets quickly look at the .tf format configuration file where resource type is "aws_instance" containing two arguments: 'instance_type' and 'ami'.

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/3a1d27df4d70b9d305e3a227b2c1af0e.js</p>

    Next, some of the Terraform files are JSON compatible, suitable for nested blocks and must have .tf.json format syntax. Let’s check out how the terraform code is declared in the .tf format.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/f98b82adda4b8c4c751f66dc17a1cdb6.js</p>

    Installing Terraform on Ubuntu Machine

    Well, Now you have a sound theoretical knowledge of what Terraform is, its configuration file structure and how they are declared. But before jumping in to learn and use Terraform, you must have terraform installed on your machine.

    Installing Terraform on Ubuntu

    • Before you install your terraform package make sure to update your already existing system packages by running the sudo apt update.

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/e773935ddccff3b17bcec76a7993ff15.js</p>

    • Next, install the zip package required to unzip the terraform zip file by running the 'apt-get install' command as shown below.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/0575dc989b11264865390ccc1135c96e.js</p>

    • Now, unzip the downloaded zip file by running unzip command.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/a9b62eba7649ac3edc60e9f5670ea720.js</p>

    • After the file is unzipped successfully, you will notice that the terraform directory is created.
    • Finally, move the executables to the 'bin' directory so that you can start using Terraform command executions.

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/1562113ed9424020c3a39548c4898ef0.js</p>

    • Verify the installation by running the following two commands:

    <p> CODE: https://gist.github.com/ShubhanjanMedhi-dev/352692a51ce7a2a2b5678eba12cb8e84.js</p>

    Terraform Backends

    Terraform backend is basically a location where terraform's state file resides. This state file has all the resource details and tracking which were provisioned or will be provisioned via terraform plan or apply command.

    There are two types of Backends,

    1. 'local' that resides where you run terraform from, it could be Linux/ windows or wherever you run it from and
    2. 'remote backend' which is like a URL or may be a different storage location like S3 bucket.

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/8ba8d2fd0df15c5ebb1cf2a07efce1de.js</p>

    <p>CODE: https://gist.github.com/ShubhanjanMedhi-dev/7c849ead415879b9d11cf26e39860d21.js</p>

    Conclusion

    In this tutorial you learnt the basics of Terraform and what you need to create or manage your infrastructure using Terraform.

    This is the first blog in our 2-part blog series on Terraform. If you wish to continue reading about Terraform, and how multiple instances can be deployed in one go using Terraform, then click here.

    Squadcast is an incident management tool that’s purpose-built for SRE. Your team can get rid of unwanted alerts, receive relevant notifications, work in collaboration using the virtual incident war rooms, and use automated tools like runbooks to eliminate toil.

    squadcast
    Written By:
    November 29, 2021
    November 29, 2021
    Share this post:
    Subscribe to our LinkedIn Newsletter to receive more educational content
    Subscribe now

    Subscribe to our latest updates

    Enter your Email Id
    Thank you! Your submission has been received!
    Oops! Something went wrong while submitting the form.
    FAQ
    More from
    Shanky
    How to deploy multiple EC2 instances in one go using Terraform
    How to deploy multiple EC2 instances in one go using Terraform
    November 30, 2021
    Learn how organizations are using Squadcast
    to maintain and improve upon their Reliability metrics
    Learn how organizations are using Squadcast to maintain and improve upon their Reliability metrics
    mapgears
    "Mapgears simplified their complex On-call Alerting process with Squadcast.
    Squadcast has helped us aggregate alerts coming in from hundreds...
    bibam
    "Bibam found their best PagerDuty alternative in Squadcast.
    By moving to Squadcast from Pagerduty, we have seen a serious reduction in alert fatigue, allowing us to focus...
    tanner
    "Squadcast helped Tanner gain system insights and boost team productivity.
    Squadcast has integrated seamlessly into our DevOps and on-call team's workflows. Thanks to their reliability...
    Alexandre Lessard
    System Analyst
    Martin do Santos
    Platform and Architecture Tech Lead
    Sandro Franchi
    CTO
    Squadcast is a leader in Incident Management on G2 Squadcast is a leader in Mid-Market IT Service Management (ITSM) Tools on G2 Squadcast is a leader in Americas IT Alerting on G2 Best IT Management Products 2022 Squadcast is a leader in Europe IT Alerting on G2 Squadcast is a leader in Mid-Market Asia Pacific Incident Management on G2 Users love Squadcast on G2
    Squadcast awarded as "Best Software" in the IT Management category by G2 🎉 Read full report here.
    What our
    customers
    have to say
    mapgears
    "Mapgears simplified their complex On-call Alerting process with Squadcast.
    Squadcast has helped us aggregate alerts coming in from hundreds of services into one single platform. We no longer have hundreds of...
    Alexandre Lessard
    System Analyst
    bibam
    "Bibam found their best PagerDuty alternative in Squadcast.
    By moving to Squadcast from Pagerduty, we have seen a serious reduction in alert fatigue, allowing us to focus...
    Martin do Santos
    Platform and Architecture Tech Lead
    tanner
    "Squadcast helped Tanner gain system insights and boost team productivity.
    Squadcast has integrated seamlessly into our DevOps and on-call team's workflows. Thanks to their reliability metrics we have...
    Sandro Franchi
    CTO
    Revamp your Incident Response.
    Peak Reliability
    Easier, Faster, More Automated with SRE.
    Incident Response Mobility
    Manage incidents on the go with Squadcast mobile app for Android and iOS devices
    google playapple store
    Squadcast is a leader in Incident Management on G2 Squadcast is a leader in Mid-Market IT Service Management (ITSM) Tools on G2 Squadcast is a leader in Americas IT Alerting on G2 Best IT Management Products 2022 Squadcast is a leader in Europe IT Alerting on G2 Squadcast is a leader in Enterprise Incident Management on G2 Users love Squadcast on G2
    Squadcast is a leader in Incident Management on G2 Squadcast is a leader in Mid-Market IT Service Management (ITSM) Tools on G2 Squadcast is a leader in Americas IT Alerting on G2
    Best IT Management Products 2022 Squadcast is a leader in Europe IT Alerting on G2 Squadcast is a leader in Enterprise Incident Management on G2
    Users love Squadcast on G2
    Copyright © Squadcast Inc. 2017-2024