Terraform and Terraform Basics
Introduction
We all know how powerful and extensively used the tool "Terraform" is. In this blog, we will go ahead and look at Terraform
what is infrastructure as a code
Infrastructure as code (IaC) is the process of managing and provisioning infrastructure through code instead of through manual processes. Infrastructure as a code is one of the best ways to automate and scale infrastructure to keep up with the rapid pace of modern software development.
What is Terraform?
Terraform provides a declarative language that allows you to define your infrastructure as code so that you can create, modify, and version your infrastructure easily. Terraform is a popular infrastructure-as-code tool that allows you to automate the provisioning and management of infrastructure resources. It uses configuration files written in the HashiCorp Configuration Language (HCL) to define the desired state of your infrastructure, and it uses various commands to apply those configurations and manage your infrastructure resources.
Why Terraform
Terraform offers many benefits and it is a widely used tool in present organizations for managing their infrastructure.
Multi-cloud and multi-provider support
Terraform can manage multi-cloud at a time like Amazon Web Services (AWS), Azure, and Google Cloud Platform(GCP) and also you can manage your on premises infrastructure. The language used in terraform was Hashi Corp Language(HCL).
Terraform is declarative management tool
There is no need to tell Terraform how to achieve the desired step-by-step you can just mention the desired state you want Terraform will automatically achieve that. So that the terraform is called a declarative management tool.
Declarative Configuration: Terraform uses a declarative configuration language, which means that users define the desired state of their infrastructure resources, rather than the specific steps required to achieve that state. This makes it easier to understand and manage complex infrastructure deployments.
Mutable and Immutable Infrastructure
Mutable infrastructure refers to upgrading the software by modifying the existing one. Immutable infrastructure refers to infrastructure that is never modified once it is created which one to choose will depend upon us.
State Management
Terraform logs(maintains) information about the resources it has created in a state file( terraform. tfstate ). This enables Terraform to know which resources are under its control and when to update and destroy them.
Reusable Infrastructure Code:
Terraform allows users to define their infrastructure resources in a reusable and modular way, using features such as modules and variables. This makes it easier to manage and maintain complex infrastructure deployments.
How Does Terraform Work?
With Terraform, users can define infrastructure resources using a simple, declarative configuration language. These resources can include virtual machines, networking components, storage resources, and more. Once the configuration is defined, Terraform can be used to create, modify, and destroy these resources in a repeatable and predictable way.
One of the key benefits of Terraform is its ability to support multiple cloud providers, as well as on-premises and open-source tools. This means that users can define infrastructure resources using a single configuration and use Terraform to manage resources across different environments.
Syntax used in HCL
Terraform uses HCL or HashiCorp Configuration Language to write infrastructure as code. HCL is designed to be easy to read and write and supports complex data structures like nested blocks, maps, and lists.
Here is a brief overview of the syntax used in HCL:
Single-line comment:
# This is a single-line comment in HCL
Multiline comment
/* This is a multiline comment in HCL */
Provider Block:
provider "aws" {
region = "ap-south-1"
}
Attributes: Attributes are key-value pairs that define the configuration of a block. They are specified within the curly braces of a block
block_type "label" {
attribute_name = "value"
another_attribute = 123
}
Strings: Strings in HCL are represented using double quotes "
.
name = "Neha"
description = "This is a sample string."
Numbers: Numeric values in HCL are written as plain integers or floating-point numbers.
age = 30
price = 12.99
Variables: In HCL, you can use variables to make your configurations more dynamic and reusable. Variables are declared and assigned values before being used. HCL supports variables, which are defined using the variable
keyword followed by a name, an optional description, and a default value.
variable "name" {
description = "Description of the variable"
default = "default value"
}
variable_name
: The name of the variable (e.g., "region").data_type
: The data type of the variable (e.g., string, number, bool, etc.).default
: The default value for the variable (optional).
Terraform Commands
a. terraform help: Terraform has a built-in help system that can be accessed from the command line for commands that you are not familiar with, or want to learn more about. You can get specific help for any specific command, Used the -help option with the relevant subcommand.
b. terraform init: The terraform init command is used to Initialise a working directory containing terraform configuration files. This is the first command that should be run after writing a new Terraform configuration or cloning an existing one from version control. It is safe to run this command multiple times.
mkdir my_terraform_project
cd my_terraform_project
# Create your main.tf file with your desired configuration
terraform init
terraform init
: Initialize a working directory
terraform init -input=true
: Ask for input if necessary
terraform init -lock=false
: Disable locking of state files during state-related operations.
c. terraform plan: The terraform plan command is used to create an execution plan. It will not modify things in infrastructure. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files. This command is a convenient way to check whether the execution plan for a set of changes matches your expectations without making any changes to real resources or the state.
terraform plan
Creates an execution plan (dry run)
terraform plan
terraform plan -out=path
save generated plan output as a file
terraform plan -destroy
Outputs a destroy plan
d. terraform apply: The terraform apply command is used to apply the changes required to reach the desired state of the configuration. Terraform apply will also write data to the terraform. tfstate file. Once the application is completed, resources are immediately available.
terraform apply
: Executes changes to the actual environment
terraform apply
terraform apply –auto-approve
: Apply changes without being prompted to enter ”yes”
terraform apply -refresh=true
: Update the state for each resource before planning and applying.
terraform apply -input=false
: Ask for input for variables if not directly set
terraform apply -var ‘foo=bar'
: Set a variable in the Terraform configuration, can be used multiple times
terraform apply -var-file=foo
: Specify a file that contains key/value pairs for variable values
terraform apply -target
: Only apply/deploy changes to the targeted resource
e. terraform refresh: The terraform refresh command reads the current settings from all managed remote objects and updates the Terraform state to match. This does not modify infrastructure but does modify the state file.
terraform refresh
f. terraform validate: The terraform validate command validates the configuration files in a directory. Validate runs checks that verify whether a configuration is syntactically valid and thus primarily useful for general verification of reusable modules, including the correctness of attribute names and value types.
terraform validate
g. terraform output: The terraform output command is used to extract the value of an output variable from the state file.
terraform output
h. terraform version: This command will print terraform version
terraform version
i. terraform destroy: The terraform destroy command is used to destroy the terraform-managed infrastructure. Terraform destroy command is not the only command through which infrastructure can be destroyed. you can remove the resource block from the configuration and run terraform apply this way you can destroy the infrastructure.
terraform destroy
Terraform Installation On AWS
For Amazon Linux EC2 server
create an ec2 instance for amazon linux
Just follow the commands given below and you get it installed on your machine.
Install Terraform
# sudo su
# yum update -y
# yum install -y yum-utils shadow-utils
# yum-config-manager --add-repo
https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
# yum -y install terraform
# terraform -version
For Ubuntu server
create an ec2 instance for Ubuntu server
Just follow the commands given below and you get it installed on your machine.
$ sudo apt-get update
$ 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
$ sudo apt update && sudo apt install terraform
$ terraform -version
hope this explanation helps you understand some of the important terminologies in Terraform.
Stay tuned for my next blog. I will keep sharing my learnings and knowledge here with you.
Let's learn together! I appreciate any comments or suggestions you may have to improve my blog content.
Thank you,
Neha Bawane
Subscribe to my newsletter
Read articles from Neha Bawane directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by