← Tất cả bài viết

Terraform

Introduction

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, provision, and manage cloud infrastructure using a simple, declarative language. Whether you're deploying resources on AWS, Azure, Google Cloud, or even on-premises, Terraform provides a unified workflow to automate and version your infrastructure.

Key Features

  • Multi-Cloud Support: Manage resources across multiple cloud providers with a single tool.
  • Declarative Syntax: Define what you want, not how to do it.
  • Version Control: Store your infrastructure code in Git, enabling collaboration and change tracking.
  • Automation: Reduce manual steps and human error by automating infrastructure changes.

Key Concepts

  • Providers: Plugins that allow Terraform to interact with APIs of cloud providers and other services (e.g., AWS, Azure, GCP).
  • Resources: The basic building blocks (e.g., servers, databases, networks) defined in your configuration files.
  • State: Terraform keeps track of your infrastructure in a state file, enabling it to detect changes and apply updates incrementally.

How Terraform Works

  1. You write configuration files describing your infrastructure using the HashiCorp Configuration Language (HCL).
  2. Terraform creates an execution plan showing what will be created, updated, or destroyed.
  3. When you apply the plan, Terraform communicates with the provider APIs to provision and manage resources.
  4. Terraform updates its state file to reflect the current infrastructure.

Basic Example

# main.tf
provider "aws" {
  region = "us-west-2"
}
 
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

This simple configuration launches an EC2 instance on AWS. You can apply it with:

terraform init
terraform apply

Common Use Cases

  • Cloud Infrastructure Provisioning: Automate the setup of servers, databases, and networks.
  • Multi-Cloud Deployments: Manage resources across AWS, Azure, GCP, and more.
  • Reusable Modules: Standardize and share infrastructure patterns across teams.
  • Automated Testing Environments: Quickly spin up and tear down test environments.

Best Practices

  • Use Modules: Organize and reuse code for common infrastructure patterns.
  • Store State Securely: Use remote backends (like S3 with DynamoDB locking) for team environments.
  • Version Control: Keep your Terraform code in a Git repository.
  • Plan Before Apply: Always run terraform plan to review changes before applying them.

Most Used Keywords in Terraform

KeywordDescription
providerSpecifies the provider (e.g., AWS, Azure, GCP) to interact with cloud APIs.
resourceDefines a piece of infrastructure to be managed (e.g., server, database).
variableDeclares input variables to parameterize configurations.
outputDefines values to be displayed after applying a configuration.
moduleGroups resources and logic for reuse across configurations.
dataFetches read-only information from providers for use elsewhere in the configuration.
localsDefines local variables within a module for intermediate values.
terraformConfigures settings for the Terraform project itself (e.g., backend, required providers).

Most Used Commands

CommandDescriptionUsage
terraform initInitializes a Terraform working directory, downloads providers and modules.terraform init
terraform planCreates an execution plan showing what Terraform will do when applied.terraform plan
terraform applyApplies the changes required to reach the desired state of the configuration.terraform apply
terraform destroyDestroys all resources managed by Terraform.terraform destroy
terraform validateValidates the syntax and internal consistency of Terraform files.terraform validate
terraform fmtRewrites Terraform configuration files to a canonical format and style.terraform fmt
terraform showShows the current state or a saved plan.terraform show
terraform stateAdvanced state management operations.terraform state list
terraform state show
terraform outputShows the values of output variables.terraform output
terraform importImports existing infrastructure into Terraform state.terraform import aws_instance.example i-12345678
terraform workspaceManages workspaces for isolating state files.terraform workspace new dev
terraform workspace select prod
terraform taintMarks a resource for recreation on next apply (deprecated in favor of -replace).terraform taint aws_instance.example
terraform refreshUpdates the state file to match the real-world infrastructure (deprecated).terraform refresh
terraform force-unlockManually unlocks the state file when Terraform operations are interrupted and leave the state locked.terraform force-unlock LOCK_ID

Conclusion

Terraform empowers teams to manage infrastructure efficiently, safely, and at scale. By adopting Infrastructure as Code, you can automate deployments, reduce errors, and enable rapid innovation. Whether you're a beginner or an experienced DevOps engineer, Terraform is a valuable tool to add to your toolkit.