Skip to content

Terraform & HCL Cheat Sheet

Search keywords: terraform init plan apply state lock taint module dynamic block backend


1. Core Workflow & Commands

Stage Command Key Flags / Usage Interview Context
Init terraform init -upgrade, -reconfigure Initializes backend, downloads providers and modules.
Validate terraform fmt / terraform validate -check Formats HCL to canonical style and verifies syntax without contacting providers.
Plan terraform plan -out=tfplan, -var-file=prod.tfvars Generates execution plan and builds dependency graph.
Apply terraform apply tfplan, -auto-approve, -target=... Applies changes. Passing a saved plan file guarantees execution determinism.
Destroy terraform destroy -target=azurerm_resource_group.rg Destroys managed infrastructure. Use -target with extreme caution.

2. Critical State Management Commands

State management questions assess whether you can fix real-world deployment blockers safely without destroying live resources.

  • List state resources:
    terraform state list
    
  • Inspect specific resource state:
    terraform state show azurerm_key_vault.shared
    
  • Move or rename a resource in state (refactoring without destruction):
    terraform state mv azurerm_s3_bucket.old_name azurerm_s3_bucket.new_name
    
  • Remove a resource from state management (without deleting the actual cloud asset):
    terraform state rm azurerm_virtual_network.vnet
    
  • Import unmanaged pre-existing infrastructure into state:
    terraform import azurerm_resource_group.rg /subscriptions/xxx/resourceGroups/my-rg
    
  • Forcefully release a stuck state lock (e.g., pipeline crashed mid-apply):
    terraform force-unlock <LOCK-ID>
    

3. Advanced HCL Constructs & Meta-Arguments

Count vs. For_Each
  • count: Creates duplicate resources based on an integer list. Weakness: Removing an item from the middle of the list causes Terraform to destroy and recreate all subsequent resources due to shifting array indices.
  • for_each: Iterates over a map or set of strings. Strength: Resources are indexed by explicit keys, so adding/removing items only affects the specific target.
Lifecycle Meta-Arguments
resource "azurerm_linux_virtual_machine" "app" {
  # ... config ...

  lifecycle {
    create_before_destroy = true  # Zero-downtime updates: provisions new before destroying old
    prevent_destroy       = true  # Guardrail against accidental terraform destroy on DBs/Vaults
    ignore_changes        = [tags, capacity] # Ignores drift caused by external tools/autoscalers
  }
}
Dynamic Blocks

Used to construct nested blocks conditionally or repeatedly based on complex variables (e.g., dynamic NSG rules):

resource "azurerm_network_security_group" "nsg" {
  name                = "app-nsg"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  dynamic "security_rule" {
    for_each = var.custom_ingress_rules
    content {
      name                       = security_rule.value.name
      priority                   = security_rule.value.priority
      direction                  = "Inbound"
      access                     = "Allow"
      protocol                   = "Tcp"
      source_port_range          = "*"
      destination_port_range     = security_rule.value.port
      source_address_prefix      = security_rule.value.cidr
      destination_address_prefix = "*"
    }
  }
}


4. Key Interview Questions & Trade-Offs

Q: What is the difference between count and for_each?

"I prefer for_each over count for resource iteration because count relies on positional array index numbers. If an item is removed from the middle of a count array, Terraform shifts all subsequent indices, attempting to destroy and recreate resources that haven't actually changed. for_each maps explicitly to keys, preventing unexpected resource replacement."

Q: How do you handle secrets in Terraform?

"Never hardcode secrets in plain text or commit .tfvars files to source control. I use remote key vaults (such as Azure Key Vault or AWS Secrets Manager) accessed via data sources or External Secrets Operators, marked as sensitive = true in variable blocks to prevent leaking in CLI stdout."

Q: What is state drift and how do you resolve it?

"State drift occurs when real-world cloud resources are modified manually outside of Terraform. Running terraform plan compares the configuration file, the state file, and the live cloud platform via API calls. If drift occurs, I evaluate whether to re-apply the IaC code to enforce the declaration or run terraform refresh / import updates if the manual change was an intentional hotfix."