DEV Community

Bartłomiej Danek
Bartłomiej Danek

Posted on • Originally published at bard.sh

Terraform and HCP Terraform

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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

topics

variables

variable "env" {
  type        = string
  description = "Deployment environment"
  default     = "dev"
}

# use it
resource "aws_instance" "web" {
  tags = { Environment = var.env }
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

outputs

output "instance_ip" {
  value = aws_instance.web.public_ip
}

output "db_password" {
  value     = aws_db_instance.main.password
  sensitive = true
}
Enter fullscreen mode Exit fullscreen mode

modules

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "main"
  cidr = "10.0.0.0/16"
}
Enter fullscreen mode Exit fullscreen mode

good practices

  • always commit .terraform.lock.hcl
  • use for_each over count for named resources
  • specify exact provider versions: ~> 5.50
  • use encrypted remote backend
  • terraform fmt before every commit
  • use moved blocks instead of destroy + recreate
  • avoid null_resource - there is usually a better way

Originally published at https://bard.sh/posts/terraform/

Top comments (0)