CUSTOMISED
Expert-led training for your team
Dismiss
Terraform for Beginners: A Step by Step Guide to Infrastructure as Code

28 August 2023

Terraform for Beginners: A Step by Step Guide to Infrastructure as Code

Infrastructure as code (IaC) has become an essential practice for managing IT infrastructure and applications. IaC enables IT teams to automate and standardize provisioning and management of infrastructure through machine-readable definition files rather than manual processes. This improves efficiency, reduces risk of human error, and facilitates collaboration.

This article is brought to you by JBI Training, the UK's leading technology training provider.   Learn more about JBI's Tech training courses including Terraform training courses that can help you improve your skills and knowledge in using Terraform. 

One of the most popular infrastructure as code tools is Terraform by HashiCorp. Terraform is an open source tool that allows you to define, provision, and manage infrastructure safely and efficiently. This beginner's guide will walk through the key concepts and usage of Terraform for managing infrastructure as code.

What is Terraform?

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Using Terraform enables DevOps teams to manage infrastructure as code and automate provisioning of resources across public cloud providers as well as on-premises solutions.

Key features of Terraform include:

  • Infrastructure as Code - Infrastructure is described using Terraform's declarative configuration language known as HashiCorp Configuration Language (HCL).
  • Execution Plans - Terraform has a planning stage that gives you an execution plan detailing what actions it will take to reach desired state before provisioning infrastructure.
  • Resource Graph - Terraform builds a resource graph from configuration files that track all dependencies between resources.
  • Change Automation - Complex changesets across resources can be applied automatically in the correct order.
  • Infrastructure State - Terraform maintains state data to track resource provisioning. This enables visibility into managed infrastructure.
  • Modular Architecture - Terraform code can be organized into reusable, shareable modules.
  • Provider Model - Providers enable Terraform to manage infrastructure across public clouds like AWS, Azure, GCP, SaaS platforms, and on-prem solutions.

Using these capabilities, Terraform provides an integrated platform for managing infrastructure as code across hybrid environments.

Benefits of Terraform

Adopting Terraform for infrastructure automation provides several key benefits:

  • Increased Efficiency - Terraform reduces manual processes and human error prone tasks through automated infrastructure provisioning.
  • Collaboration - Infrastructure as code enables collaboration across teams through shared Terraform configuration files.
  • Consistent Environments - Infrastructure can be replicated consistently across environments using parameterized Terraform modules.
  • Version Control - Terraform files can be stored in version control to track changes and enable rollbacks.
  • Tool Agnostic - Terraform works across all major cloud providers as well as virtualization platforms, container orchestration tools, and more.

By codifying and automating infrastructure provisioning and management with Terraform, organizations can gain improved efficiency, reliability, and agility.

Prerequisites

To start using Terraform, you need:

  • Access to infrastructure - This may include cloud platforms like AWS, Azure, GCP or on-prem resources.
  • Terraform downloaded - Go to terraform.io to download the Terraform binary for your OS.
  • IAM user credentials - For provisioning cloud resources, you need credentials for the target platform like access keys for AWS.
  • Code editor - A text editor for writing Terraform files like Visual Studio Code.

With these prerequisites met, you're ready to start learning Terraform basics.

Getting Started with Terraform

Getting started with Terraform involves understanding the basics of how it works along with the following steps:

  1. Initialize working directory
  2. Write infrastructure as code
  3. Create execution plan
  4. Apply changes

Let's look at each of these steps in more detail:

Initialize Working Directory

The first step is to initialize a new or existing Terraform working directory using the terraform init command.

This will install any required providers defined in the configuration. Providers enable Terraform to interact with the target infrastructure.

For example:

terraform init

This installs the providers required for provisioning infrastructure defined in the Terraform files in the working directory.

Write Infrastructure as Code

Next, you need to author the infrastructure as code that defines the desired resources.

Terraform configuration files use the .tf file extension and are written in HashiCorp Configuration Language (HCL) syntax.

For example, a simple AWS S3 bucket can be defined as:


resource "aws_s3_bucket" "data" {
  bucket = "my-tf-test-bucket" 
  acl    = "private"
}

This defines the S3 bucket configuration that can be applied.

Create Execution Plan

Before applying any changes, Terraform lets you generate an execution plan using:

terraform plan

This displays what actions Terraform will take to reach desired state defined in the configuration. Reviewing execution plans prevents unexpected changes.

Apply Changes

Finally, the infrastructure can be provisioned by applying the Terraform configuration:

terraform apply 

This will make the changes needed to reach desired state. New resources defined in the configuration will be created.

With these basics, you can start automating infrastructure provisioning with Terraform infrastructure as code. Next let's look at provisioning some sample AWS resources.

Provisioning AWS Infrastructure

To start automating infrastructure provisioning with Terraform, we'll walk through deploying some sample AWS resources:

  1. Configure AWS provider
  2. Create S3 bucket
  3. Provision EC2 instance
  4. Output instance IP

Configure AWS Provider

The first step is configuring authentication for the AWS provider by adding your access keys:


provider "aws" {
  access_key = "my-access-key"
  secret_key = "my-secret-key"
  region     = "us-east-1" 
}

This configures credentials for Terraform to interface with AWS.

Create S3 Bucket

Next we can define an S3 bucket resource:


resource "aws_s3_bucket" "data" {
  bucket = "my-tf-test-bucket"
  acl    = "private" 
}

This will create an S3 bucket when applied.

Provision EC2 Instance

We can also provision an EC2 server instance:


resource "aws_instance" "web" {
  ami           = "ami-047a51fa27710816e"
  instance_type = "t2.micro" 
}

This defines an EC2 instance using a stock Ubuntu AMI that will be launched when applied.

Output Instance IP

Finally, we can output the public IP address of the EC2 instance like so:


output "instance_ip" {
  value = aws_instance.web.public_ip
}

This output can be queried after apply to check the IP address.

After writing these Terraform configuration files, we can initialize, plan, and apply to provision these AWS resources.

Modifying Infrastructure

A key benefit of infrastructure as code is the ability to update and iterate on infrastructure by modifying configuration.

When Terraform files are updated with new resource attributes or properties, Terraform can incrementally apply changes:

  1. Modify resource configs
  2. Preview changes with terraform plan
  3. Apply changes with terraform apply

For example, to increase EC2 instance size:


# modify instance_type
resource "aws_instance" "web" {
  instance_type = "t2.large" 
}

# review changes  
terraform plan

# apply changes
terraform apply

By modifying the desired state in configuration files, resources can easily be changed as needed.

Destroying Infrastructure

To clean up provisioned infrastructure, use:

terraform destroy

This terminates all the resources managed by the Terraform state. Destroying resources at the end of a test or development environment is best practice to avoid unnecessary charges.

Reusable Modules

Terraform supports modular configuration to make reuse and sharing of common infrastructure patterns easier. Modules encapsulate Terraform configurations for a set of resources and expose variables and outputs.

For example, to use a module to deploy a reusable VPC configuration:


module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "my-vpc" 
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b", "us-east-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

}

This leverages a reusable VPC module published in the Terraform Registry instead of writing custom configuration. Modules make Terraform configurations modular and shareable.

Variables

Terraform variables enable parameterization of configurations for reuse and customization:


variable "instance_type" {
  default = "t2.micro" 
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
}

Variables can be defined with custom values when running Terraform commands:


terraform apply -var 'instance_type=t2.large'

Input variables make configurations customizable and avoid hard coding values.

Workspaces

Terraform workspaces isolate state files to enable managing distinct infrastructure resources for dev, test, prod, or features:


# create dev workspace  
terraform workspace new dev

# create prod workspace
terraform workspace new prod

# provision resources in dev
terraform apply

# switch to prod   
terraform workspace select prod

# provision prod resources 
terraform apply

Workspaces provide isolation for managing infrastructure across environments and features.

Remote State

Terraform remote state enables collaborating in a team by storing the state file remotely in a backend like S3:


terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "network/terraform.tfstate"
    region = "us-east-2"
  }
}

This allows having a single source of truth for state across a team.

Conclusion

Infrastructure as code with Terraform provides a powerful solution for automating infrastructure provisioning, management, and orchestration. With this beginner's guide, you should have a foundational understanding of getting started with Terraform to manage infrastructure as code.

Some next steps for advancing your skills:

  • Try using Terraform modules for reusable infrastructure patterns
  • Explore provisioning resources across AWS, GCP, Azure, Kubernetes, and more
  • Use Terraform in CI/CD pipelines for automated deployments
  • Manage and collaborate on shared infrastructure state with remote backends
  • Leverage Terraform Cloud for advanced collaboration features

Adopting infrastructure as code practices with Terraform unlocks innovation velocity, efficiency, and reliability for infrastructure changes across hybrid environments. This gives teams a competitive advantage for delivering and scaling applications faster.

Frequently Asked Questions

What skills do I need to use Terraform?

Experience with infrastructure provisioning and basic programming skills like variables, loops, conditionals help. Terraform itself is easy to learn if you understand key concepts like infrastructure as code.

Can Terraform provision on-premises infrastructure?

Yes, Terraform can manage on-prem resources using the VMware vSphere provider. There are also providers for networking gear, Kubernetes clusters, docker, and more.

How does Terraform work with version control?

Terraform configuration files can be committed to version control like Git to track changes. Remote state can also be stored in a backend that supports locking like S3.

Can I use Terraform with my existing automation tools?

Terraform can integrate with configuration management tools like Ansible, Packer, custom scripts, CI/CD pipelines, and more through provisioners.

What cloud providers does Terraform support?

Terraform supports all major cloud platforms including AWS, Azure, GCP, DigitalOcean, OpenStack as well as SaaS providers like Datadog, Kubernetes, and more.

Our next article can be found here:  An Introduction to Terraform Modules for Reusable Composable Infrastructure 

In today's dynamic infrastructure environment, Terraform is an invaluable tool for operations teams and developers alike. Its capabilities for declaratively defining, provisioning, and managing infrastructure as code can drive more efficient, collaborative infrastructure management.

Whether you're just starting out with infrastructure-as-code or looking to improve an existing Terraform implementation, our Terraform training courses at JBI Training can help you master this powerful platform. So why wait? Embrace the power of infrastructure-as-code and transform your infrastructure workflows today.

Start your learning journey today with the Terraform courses at JB International and unlock the potential of infrastructure-as-code at your fingertips, including:

Terraform: Learn how to use Terraform to build, change, and version infrastructure safely and efficiently. 

DevOps: Gain comprehensive DevOps Skills - with AWS, Docker, Ansible and Terraform

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course