Introduction
Terraform is a open source Infrastructure as code (IaC) tool created by HashiCorp. It allows you to configure infrastructure using hashicorp configuration language (HCL) or json. Baisc overview of terraform is below.
Core Concepts
- IaC: Practice of managing and provisioning Infrastruture through code rather than manual process.
- Providers: Plugins that terraform uses to intract with APIs of cloud platforms and other services (AWS, Azure, GCP).
- Resources: The components for your infrastruture that you manage (EC2 instances, S3, VPC).
- Modules: Reusable configuration that can be used to create more complex setup or share infrastructure.
- State: Terraform keeps track of resources it manages in a state file. This file is used to map your configuration with real infrastruture.
Basic Workflow
-
Write configuration file:
- Terraform configurations are written in .tf file using HCL.
- Example:
provider "aws" {
region= "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-12312"
instance_type = "t2.micro"
}
-
Intialize your project
- Run terraform init to intialize your working directory. This downloads the necessary provider plugins and sets up your project.
terraform init -
Plan Changes:
- Run terraform plan to see what changes will do to your infrastruture bsed on your configuration files.
terraform plan -
Apply changes:
- Run terraform apply to apply the changes required to reach the desired state defined in your configuration file.
terraform apply -
Destroy Infrastruture
- When you want to remove all resources defined in your configration.
terraform destroy
Key commands
- terraform init
- terraform plan
- terraform apply
- terraform fmt: format terraform code style
- terraform validate: validates the syntax and internal consistency of terraform code
- terraform destroy
- terraform taint: Mark a resource for recreation in next apply
- terraform untaint
- terraform output: retrieves the output values from most recent apply.
- terraform workspace list/new/select : manage environments
- terraform graph: generates a visual representation of the dependency graph of your resources.
- terraform state list/show/rm
Best practices
- Version Control: store all your configration file in GIT
- State Management: Use remote state storage (AWS S3 dynamodb) to manage your state files.
- Modules: Use and create modules to organize and reuse the code.
- Variables: Use variables to make your configration more flexible and reusable.