what is terraform
Terraform is a CLI tool for building and managing infrastructure as code. You describe what you want, it figures out how to get there.
- written in HCL
- no enforced file structure
- dependencies between resources are expressed in code
- API wrapper for AWS, GCP, Azure, Kubernetes, GitHub, and many more
- immutable infrastructure by default
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.small"
}
CLI
terraform init # initialize, download providers
terraform plan # dry run - shows what will change
terraform apply # apply changes
terraform destroy # destroy everything
terraform validate # validate config files
terraform fmt # auto-format
terraform state # inspect and manipulate state
terraform output # show outputs
terraform console # interactive expression evaluator
topics
- State, S3 backend and locking
- Variables, locals, outputs
- count vs for_each
- for, if expressions
- Data sources
- Dynamic blocks
- Lifecycle rules
- .terraform.lock.hcl
- Modules
variables
variable "env" {
type = string
description = "Deployment environment"
default = "dev"
}
# use it
resource "aws_instance" "web" {
tags = { Environment = var.env }
}
Pass values via terraform.tfvars, -var flag, or TF_VAR_ env vars.
locals
locals {
prefix = "${var.env}-${var.region}"
}
resource "aws_s3_bucket" "logs" {
bucket = "${local.prefix}-logs"
}
outputs
output "instance_ip" {
value = aws_instance.web.public_ip
}
output "db_password" {
value = aws_db_instance.main.password
sensitive = true
}
modules
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
name = "main"
cidr = "10.0.0.0/16"
}
good practices
- always commit
.terraform.lock.hcl - use
for_eachovercountfor named resources - specify exact provider versions:
~> 5.50 - use encrypted remote backend
-
terraform fmtbefore every commit - use
movedblocks instead of destroy + recreate - avoid
null_resource- there is usually a better way
Originally published at https://bard.sh/posts/terraform/
Top comments (0)