Terraform is an Infrastructure as Code (IaC) tool used for building, changing, and versioning infrastructure efficiently. Below is a cheat sheet for Terraform commands and configurations:
Terraform Configuration
Initialize a Terraform Working Directory:
terraform init
Create or Update Infrastructure:
terraform apply
Plan Changes:
terraform plan
Destroy Infrastructure:
terraform destroy
Show Output Values:
terraform show
Terraform Configuration File (main.tf
)
# main.tf
# Provider Configuration
provider "aws" {
region = "us-east-1"
}
# Resource Definition
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
# Variable Declaration
variable "example_var" {
type = string
description = "An example variable"
default = "default_value"
}
# Output Declaration
output "example_output" {
value = aws_instance.example.id
}
Terraform Variables (variables.tf
)
# variables.tf
# Variable Declaration
variable "region" {
type = string
description = "AWS region"
default = "us-east-1"
}
Terraform State
Show Terraform State:
terraform show
Manually Import Existing Resources:
terraform import aws_instance.example i-instance-id
Terraform Modules
Create a Module:
- Create a directory with the module code and a
main.tf
file.
modules/
├── example_module/
├── main.tf
Use a Module in Your Configuration:
# main.tf
module "example" {
source = "./modules/example_module"
# module specific variables
}
Terraform Commands
Validate Configuration:
terraform validate
Format Configuration:
terraform fmt
Upgrade Terraform Providers:
terraform init -upgrade
Debug Output:
TF_LOG=DEBUG terraform apply
Terraform Remote Backends
Configure Remote Backend (e.g., AWS S3):
# main.tf
terraform {
backend "s3" {
bucket = "your-bucket-name"
key = "path/to/terraform.tfstate"
region = "us-east-1"
}
}
Initialize Terraform with Remote Backend:
terraform init -backend-config=backend.tfvars
Terraform Workspaces
Create a Workspace:
terraform workspace new dev
Select a Workspace:
terraform workspace select dev
List Workspaces:
terraform workspace list
Important Notes
- Use
terraform plan
to review changes before applying. - State files should be stored securely, especially when using remote backends.
- Modules enable code reuse and maintainability.
- Terraform supports various providers, not just AWS.
- Variables and outputs help parameterize and share values.
- Workspaces facilitate managing multiple environments.
This cheat sheet provides an introduction to Terraform commands and configurations. For more detailed information, refer to the official Terraform documentation.