How to use Terraform in Linux environments to automate infrastructure

Introduction to Terraform in Linux

Terraform is an infrastructure tool as a code (IaC) that allows to define, provide and manage cloud and on-premises resources by means of declarative configuration files. In a Linux environment, its use becomes even more powerful thanks to natural integration with the command line, shell scripts and package management systems.

Terraform installation in popular Linux distributions

The steps vary slightly according to distribution, but the overall process is as follows:

  • Download the official binary package from HashiCorp's page.
  • Uncompress the file and move the binary to a directory included in $PATH, for example/usr/local/bin.
  • Check the installation withterraform -version.

In Ubuntu or Debian you can use the official repository:

sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /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
sudo apt-get update && sudo apt-get install terraform

In Fedora, CentOS or RHEL the package manager is useddnforyumwith the HashiCorp repository:

sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
sudo dnf install -y terraform

Initial working environment configuration

Once installed, it is recommended to create a dedicated directory for each Terraform project:

mkdir -p ~/projects/infra-web && cd ~/projects/infra-web

Within that directory, initialize the project with:

terraform init

This command download the necessary suppliers (e.g. the AWS, Azure or Google Cloud supplier) and prepare the backend where the state will be stored.

Writing your first configuration

Configuration files use HCL syntax (HashiCorp Configuration Language). A simple example to create an EC2 instance in AWS:

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "servidor-web"
  }
}

Save this content in a called filemain.tf. Then check what Terraform plans to do:

terraform plan

If everything looks right, apply the changes:

terraform apply

Terraform will ask for confirmation before creating resources.

Status management and teamwork

The fileterraform.tfstatecontains the current state of the infrastructure. For equipment, it is essential to store this state in a remote backend, such as Amazon S3, Azure Blob Storage or HashiCorp Consul, so that all members access the same source of truth.

An example of backend configuration inbackend.tf:

terraform {
  backend "s3" {
    bucket = "mi-terraform-state"
    key    = "infra-web/terraform.tfstate"
    region = "us-east-1"
  }
}

After defining the backend, runterraform initagain to migrate the local state to the remote.

Modules and reuse

The modules allow reusable configurations to be encapsulated. You can create a module for a web instance and use it in several environments.

Basic structure of a module:

modules/
└─ web-instance/
   ├─ main.tf
   ├─ variables.tf
   └─ outputs.tf

Inmain.tfof the module:

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

variable "ami_id" {}

variable "instance_name" {}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = var.instance_name
  }
}

Then from the root, you call it this way:

module "web" {
  source = "./modules/web-instance"
  ami_id = "ami-0c55b159cbfafe1f0"
  instance_name = "servidor-web"
}

This way you avoid duplicating code and maintain consistency.

Working with workspaces for multiple environments

Terraform workspaces allow to maintain several isolated states within the same configuration directory, useful for separating development, staging and production.

Create and change workspace:

terraform workspace new dev
terraform workspace select dev

You can use the variable.terraform.workspaceto adjust behavior according to the environment:

resource "aws_instance" "web" {
  instance_type = terraform.workspace == "prod" ? "t3.large" : "t2.micro"
  # ... resto de la configuración
}

Remember that each workspace has its own fileterraform.tfstate.dor, if you use remote backend, a separate state.

Good practices when using Terraform in Linux

  • Keep your configuration files under version control (Git).
  • Useterraform fmtto maintain a consistent style.
  • Check the plans withterraform planbefore applying in production environments.
  • Employment and variable files (terraform.tfvars) or environment variables to avoid hard-coding secrets.
  • Automates the execution using CI / CD pipelines (GitHub Actions, GitLab CI) that are run in Linux agents.
  • Scan your code withterraform validateand security tools like tfsec or Checkov.

Conclusion

Terraform has become an indispensable ally for system administrators and developers working in Linux. Its ability to describe the infrastructure as a code, combined with the power and flexibility of the Linux terminal, allows to create reproducible, scalable and secure environments with few commands. Following the installation, configuration and best practice steps described in this article, you will be ready to take your automation to the next level.

This work is under aCreative Commons License Attribution 4.0 International for Francesc Roig francesc @ vivaldi.net.

EnglishenEnglishEnglish