Terraform (PT-1)

As easy as it gets!

Yash Thube
Nerd For Tech
9 min readJan 24, 2024

--

Infrastructure as Code (IAC)

  • What is it? IAC is like writing a recipe for your computer systems and network setup, but instead of following the recipe manually, you let a program do it for you.
  • Why use it? It makes managing and setting up computer systems easier, faster, and less error-prone because everything is defined in a file or files.

Terraform

  • What is it? Terraform is a tool that helps you use IAC. It’s like a wand for setting up and managing your computer infrastructure.
  • How does it work? You write a file that describes what you want your computer systems to look like (like a blueprint). Terraform then reads this file, figures out what needs to be done, and makes it happen.
  • What can it do? Terraform can create and manage all kinds of things — from basic computer stuff like virtual machines to more advanced things like networks and security setups.
  • Why use it? It saves time and reduces mistakes. If you need to set up a bunch of computers, you just tell Terraform what you want, and it takes care of the details.
  • Picture it like creating a to-do list for your computer systems, and Terraform is the efficient assistant that completes the tasks on your list, turning your plans into reality.

Manage Infrastructure

  • Think of managing infrastructure as telling your computer how you want things set up, like creating a virtual playground for your applications to run.

Variable Types

  • When you’re giving instructions to Terraform, you might need different types of information. Here are the types of information you can use:
  • Strings: Words and text.
  • Numbers: Just like in math.
  • Boolean: It’s like a light switch, either on or off (true or false).
  • List: A list of things, like items in a shopping list.
  • Maps: Like a dictionary, connecting one thing to another.

Setting Up Variables

  • When you tell Terraform what you want, you can use variables to customize things. For example:
  • vpcname: A word (string) representing the name of your virtual playground. If you don't tell Terraform, it'll use "myvpc" by default.
  • enabled: A switch (boolean) that's turned on by default. If you don't say otherwise, it stays on.
  • sshport: A number representing the door (port) where you can enter your virtual playground. It's set to 22 by default.
  • For numbers and booleans, you don’t need to put them in double quotes. Terraform understands them even without the quotes. For example, 5 and "5" both work for numbers.
  • In a nutshell, it’s like telling Terraform what you want to build and giving it some options to customize your setup. The defaults are like the “usual” choices, but you can change them if you want something different.

Variables List

  • Think of this as a shopping list. You can have multiple items, and each item has a position. The first item is at position 0, the second at position 1, and so on.
  • Example: mylist is a list of strings with default values "Value1" and "Value2". To get the first value, you say var.mylist[0].

Variables Map

  • Imagine a map like a dictionary where you have a key and a value. You use the key to find the associated value.
  • Example: mymap is a map with keys "Key1" and "Key2" having values "Value1" and "Value2" respectively. To get "Value1", you say var.mymap["Key1"].

Input Variables

  • When you want to let someone set a variable manually (like giving a name to your VPC), you use input variables. It’s like asking for user input.
  • Example: vpc_name is a string variable where the user can set the VPC name. When running Terraform, it prompts the user to enter a value.

Outputs

  • Outputs are like showing the results after you’ve built something. You might not know the exact values until you’ve actually created things (like getting the ID of a VPC after creating it).
  • Example: After creating a VPC, you might have an output that shows the VPC ID.

Local Values

  • Think of local values as giving a nickname to something you might use a lot in your instructions to Terraform. It’s like having a handy shortcut so you don’t have to keep repeating the same thing over and over.
  • Declaration:
  • When you declare local values, you’re basically saying, “Hey Terraform, when I say service_name, I mean 'forum', and when I say owner, I mean 'Community Team'."

Use Case

  • You use local values when you have something you’re going to mention a lot in your instructions, and you want a simple way to refer to it. It’s like a mini cheat sheet for your Terraform setup.

When to Use

  • Use local values when you find yourself repeating the same information many times. However, don’t go overboard. Use them wisely, only for things you’re likely to change later. It’s all about making your setup easy to understand and change in the future.

Remember

  • Local values are like your own little nicknames for things. They’re helpful but use them just enough to make your life easier without making things confusing for others.

Environment Variables

  • It’s like giving Terraform a heads-up before it does something. You can set variables as exports before running Terraform. Handy for keeping secret stuff secure.
  • Example: export TF_VAR_vpcname=envvpc

CLI Variables

  • You can also tell Terraform what variables to use right from the command line.
  • Example: terraform plan -var="vpcname=cliname"

TFVars Files

  • Imagine having a cheat sheet for Terraform in a file. You create a file called terraform.tfvars where you list your variables and their values. It's like a simple recipe for Terraform.
  • Example:
vpcname = "tfvarsname"
port = 22
policy = {
test = 1
debug = "true"
}

This file helps Terraform understand what values to use. The .tf file declares that these variables exist.

Summary

  • Environment Variables: Tell Terraform beforehand with exports.
  • CLI Variables: Pass variable values directly in the command line.
  • TFVars Files: Use a separate file with a list of your variable values.

Think of it like leaving notes for Terraform. Whether you whisper it in its ear (environment), write it on a paper (CLI), or give it a cheat sheet (TFVars file), Terraform just needs to know what you want.

Feeling a bit worn out? No worries! Take a breather because our journey is just getting started. We’ve got plenty more to explore.

Auto TFVars

  • Imagine you have a friend who always knows what to bring to the party. dev.auto.tfvars is like that friend. Terraform checks this file after looking in terraform.tfvars. It's a handy backup with additional settings.

Multiple Value Files

  • Think of different environments like different rooms in a house. If you want specific settings for each room, you can use separate files like prod.tfvars. When you run Terraform, you tell it to pick up values from these files.
  • Example: terraform plan -var-file=prod.tfvars

Load Order

  • Terraform loads variables in a specific order:
  1. Command-line options (-var and -var-file).
  2. Files ending with .auto.tfvars or .auto.tfvars.json.
  3. terraform.tfvars.json.
  4. terraform.tfvars.
  5. Environment variables.

Versioning

  • Picture it like telling Terraform, “Hey, only accept certain versions of yourself.” The required_version setting helps ensure your Terraform script works with the right version.
  • Example: required_version = ">= 0.12"

Provider Version Requirement

  • Sometimes, you need to specify the version of a specific tool within Terraform. It’s like saying, “For the AWS part, only accept this version or higher.”
  • Example: version = ">= 2.9.0" for the AWS provider.

In Summary

  • Auto TFVars is like a backup friend with extra goodies.
  • Multiple Value Files are like setting up different rooms with specific settings.
  • Load Order is how Terraform puts on its “shoes” (loads variables).
  • Versioning is telling Terraform which versions are its best friends.
  • Provider Version Requirement is specifying the version of a specific tool.

Multiple Provider Setup

  • Imagine you have friends in different cities, and each friend knows a different set of secrets. In Terraform, you can have multiple AWS providers with different regions.
  • Example:
provider "aws" {
region = "us-east-1"
}

provider "aws" {
region = "us-west-1"
alias = "ireland"
}

resource "aws_vpc" "irlvpc" {
cidr_block = "10.0.0.0/16"
provider = "aws.ireland"
}

Here, ireland is like a special friend in a different region. When creating a resource (like a VPC), you tell Terraform to use this specific friend (provider = "aws.ireland").

Provisioners

  • Provisioners are like choreographers for your infrastructure dance. They help prepare servers or other objects for service, either on your local machine or a remote one.
  • Example:
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
command = "echo The server's IP address is ${self.private_ip}"
}
}

In this example, when an AWS instance is created, a provisioner (local-exec) is used to execute a command locally (on your machine).

Creation-Time Provisioners

  • Imagine setting up a new computer. Creation-time provisioners are like the first things you do when you turn it on. They run only when the resource is created and help with the initial setup.
  • Example:
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
command = "echo 'Creation-time provisioner'"
}
}

If a creation-time provisioner fails, Terraform marks the resource as tainted. It means that next time you apply changes, Terraform plans to destroy and recreate it.

Destroy-Time Provisioners

  • Now, imagine shutting down that computer. Destroy-time provisioners are like the last things you do before saying goodbye. They run when the resource is destroyed.
  • Example:
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
when = "destroy"
command = "echo 'Destroy-time provisioner'"
}
}

If destroy provisioners fail, Terraform errors and retries next time.

Local vs. Remote Exec

  • Think of local-exec as doing things on your computer (local machine), like creating an SSH key or running a script.
  • Example (local-exec):
resource "null_resource" "generate-sshkey" {
provisioner "local-exec" {
command = "ssh-keygen -b 4096 -t rsa -C 'terraform-example' -N '' -f ./my-ssh-key"
}
}

Remote-exec is like having a remote assistant do things on a computer somewhere else (on the remote instance), like moving files or changing permissions.

  • Example (remote-exec):
resource "aws_instance" "example" {
# ...
provisioner "remote-exec" {
inline = [
"mv /tmp/authorized_keys /root/.ssh/authorized_keys",
"chmod 600 /root/.ssh/authorized_keys",
]
}
}

Let’s simplify the Terraform workflow for different types of users

1. Individual:

  • Write: Imagine you’re like an architect sketching a blueprint. You create Terraform files, describing what you want.
  • Plan: Before building, you want to double-check your blueprint. Run terraform plan to make sure everything looks good.
  • Create: Now it’s construction time! Execute terraform apply to create the infrastructure based on your plan.

2. Team:

  • Write: Like a team of architects collaborating on a project. Everyone writes Terraform files and checks out the latest code.
  • Plan: Before major changes, the team creates a pull request. Run terraform plan to see what impact the changes will have.
  • Create: Once the team agrees on the plan, merge the pull request, and execute terraform apply to bring the changes to life.

3. Terraform Cloud:

  • Write: Instead of each architect having their own sketchpad, everyone uses a shared development environment on Terraform Cloud. State files, variables, and secrets are stored there.
  • Plan: When a pull request is raised, Terraform Cloud automatically runs terraform plan. It's like having an automated assistant checking the blueprints.
  • Create: Before merging, a second plan is run for approval. Once approved, Terraform Cloud executes terraform apply to create or update the infrastructure.

It’s all about ensuring a smooth transition from planning to creation, whether you’re working alone, with a team, or leveraging the capabilities of Terraform Cloud for a streamlined workflow.

Let’s simplify the key Terraform commands

1. terraform init:

  • Imagine this as setting up your workspace. It’s like preparing your desk before starting work.
  • What it does: Initializes a working directory containing Terraform configuration files. It sets up the backend and configuration settings.
  • Useful tip: Safe to run multiple times, won’t delete your existing work.

2. terraform validate:

  • Think of this as checking your blueprint for errors before starting construction.
  • What it does: Validates configuration files for syntax and internal consistency. It’s like ensuring your plan makes sense before execution.
  • Useful tip: No remote access; it’s like a pre-flight check for your Terraform configurations.

3. terraform plan:

  • Picture this as a project manager creating a detailed plan before actual construction begins.
  • What it does: Creates an execution plan. Terraform figures out what actions are needed to achieve the desired infrastructure state.
  • Useful tip: Refreshes the state and shows you the proposed changes without actually applying them.

4. terraform apply:

  • Now, it’s like executing the construction plan and building your infrastructure.
  • What it does: Applies the changes to reach the desired state specified in the configuration files. It executes the pre-determined actions generated by a terraform plan.
  • Useful tip: The real action. After planning, executing terraform apply brings your infrastructure to life.

5. terraform destroy:

  • Imagine having a demolition crew after your project is done.
  • What it does: Destroys the Terraform-managed infrastructure. It’s like taking down the building after it served its purpose.
  • Useful tip: Use cautiously; it will tear down everything managed by Terraform.

Stay tuned for the next one!!

--

--

Yash Thube
Nerd For Tech

Exploring Cloud Possibilities ☁️ Harnessing AI/ML Opportunities ✔️