How to Install Terraform on Ubuntu 22.04 Step-by-Step

In this guide, we will cover how to install Terraform on Ubuntu 22.04 and provide you with some useful Terraform examples to kickstart your journey into the world of infrastructure automation.

Terraform, an open-source Infrastructure as Code (IaC) tool, has gained immense popularity for its ability to automate and manage infrastructure deployments efficiently. If you’re running Ubuntu 22.04 and want to harness the power of Terraform, you’re in the right place.

Prerequisites

  • A System with pre-installed Ubuntu 22.04
  • Sudo User with admin rights
  • Stable Internet Connectivity

Installing Terraform on Ubuntu 22.04

1) Add Terrafrom APT Repository

Terraform package is not available in default package repositories of Ubuntu 22.04. So, for its installation, we must add hashicorp apt repository.

First download the repository GPG key and then add hashicorp apt repository. Run below set of commands.

$ wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
$ echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list

Add-Hashicorp-Terrafrom-Repository-Ubuntu-22-04

2) Install Terraform using Apt Command

Run beneath apt commands to install terraform,

$ sudo apt update
$ sudo apt install terraform -y

Install-Terraform-Ubuntu-22-04

Post terraform installation, verify its version,

$ terraform version
Terraform v1.5.7
on linux_amd64
$

Test Terraform Installation

To test terraform installation, we will try to execute below terraform example. But before that let’s understand its important files.

  • main.tf : It is the main configuration file containing resource definition
  • variables.tf : It contains variables declarations.
  • outputs.tf : This contains output from the resources.
  • provider.tf : It contains provider definition.

Example : Using Local provider, create a file nix.txt.

$ mkdir iac01 && cd iac01
$ vi main.tf
resource "local_file" "distros" {
  filename = "/tmp/nix.txt"
  content = "I Love Linux distros like Ubuntu. Debian, RHEL, Rocky Linux & Kali Linux etc"
}

Save and close the file

Next initialize the terraform, plan and apply.

$ terraform init

Terraform-Init-Local-Provider-Example

$ terraform plan

Terraform-Plan-Local-Provider-Example

$ terraform apply

Terrafrom-Apply-Local-Provider-Example

Verify whether the file has been created or not.

$ ls -l /tmp/nix.txt
-rwxrwxr-x 1 linuxbuzz linuxbuzz 76 Sep 18 12:47 /tmp/nix.txt
$

To destroy this resource, run

$ terraform destroy

That’s all from this guide, I hope you have found it informative and useful. Kindly do post your feedback and queries in below comments section.

Also Read: How to Set Static IP Address on Ubuntu 22.04

Leave a Comment

twenty − 6 =