Skip to the content.

Terraform Cheatsheets

Cheatsheets

Terraform Format:

terraform fmt

Validate terraform syntax:

terraform validate

Validate terraform syntax and skip backend validation:

terraform validate -backend=false

Initialize and download providers:

terraform init

Terraform plan to review what will be changed:

terraform plan

Terraform Apply to create/delete resources:

terraform apply

Merge function

In this scenario, you can have default tags, but if you want to replace Environment, you can define the var.environment and include it in the merge function.

variable "default_tags" {
  default = {
    ManagedBy   = "terraform"
    Environment = "local"
  }
}

variable "name" {
  default = "testing"
}

variable "environment" {
  default = "dev"
}

output "merge_tags" {
  value = "${merge(var.default_tags, tomap({"Name" = "prefix-${var.name}", "Environment" = "${var.environment}"}))}"
}

Validations

Length:

variable "service_name" {
  type = string

  validation {
    condition     = length(var.service_name) < 40
    error_message = "The service_name value cant be more than 40 characters."
  }
}

Regex match:

variable "env_name" {
  type = string
  default = null
  validation {
    condition  = can(regex("^(dev|staging|production|ephemeral-.*)+$", var.env_name))
    error_message = "For the env_name value only dev, staging, production and ephemeral-* are allowed."
  }
}

Booleans to control

We want to use a boolean variable to set the number:

warm_pool = {
  pool_state                  = "Running"
  min_size                    = var.warm_pool_enabled ? 1 : 0
  max_group_prepared_capacity = var.warm_pool_enabled ? 1 : 0
}

Resources

Terraform Tutorials:

Terraform Examples:

Learn Guides:

Terraform Cheatsheets

Terraform AWS Workshops:

Terraform with Ansible Examples:

Terraform States:

Terraform Providers: