Terraform commands Quick Reference

Terraform commands Quick Reference

The Goal of this article is to provide you with a quick reference to the terraform commands

Initialise a Terraform working directory

terraform init

Generate and show an execution plan

terraform plan         # dry run

Builds or changes the infrastructure

terraform apply
terraform refresh      # sync state with remote resources

Inspect Terraform state or plan

terraform show

Destroy Terraform-managed infrastructure

terraform destroy

Rewrites config files to a canonical format

terraform fmt

Run Terraform apply without prompt

terraform apply -auto-approve

This command is used to update local state file against real resources. Run the refresh command before terraform console

terraform refresh

Interactive console for Terraform interpolations. Console environment to test local variables and resources

terraform console

Validates the Terraform files

terraform validate     # validate .tf file

Manually mark a resource for recreation

terraform taint        # mark resource for recreation

Manually unmark a resource as tainted

terraform untaint

Graph command used to display the visual graph of Terraform resources

terraform graph
terraform state push   # e.g. force push state to S3 bucket
terraform state pull > terraform.tfstate  # create a local state copy

Clean up leftover locks from hard-cancelled run

Change verbosity by setting environment variable TF_LOG

terraform force-unlock <lock-id-guid>

export TF_LOG=INFO

For linting

 terraform fmt <file>           # reformat .tf file
 terraform fmt --check <file>   # check for correct formatting

Configuration via Environment

While most of the configuration should reside in .tfvars files you might want to inject some config values from environment like this:

export TF_VAR_<my variable>=<my value>

Workspace Management

Terraform workspaces allow for the management of two or more different environments i.e. Dev or Prod separately without affecting the state of either environment.

terraform workspace new dev   
terraform workspace new test
terraform workspace new prod
terraform workspace select dev
terraform workspace select default  
terraform workspace select prod

More on using terraform workspaces as environments %[azhercan.com/terraform-workspace]

Managing Multi-Region Deployments

Recovering Lost State

One of the worst things that you happen is loosing the terraform state. In such a case you can

Prints a tree of the providers used in the configuration

terraform providers

Read output from a state file

terraform output

Import existing infrastructure into Terraform

terraform import <address> <id>

For example

terraform import aws_instance.myec2instance i-075c8d21cc91308dc

to let terraform reconstruct the resource state. Finally perform a

terraform state push

as import only imports into a local state file, even if you have an S3 bucket defined for keeping state!

To avoid this use S3 bucket with versioning enabled for keeping state.

Drift Management

Terraform doesn’t really do much drift management. Only some resource attributes are checked. All detected drift is fixed by “apply”.

Manually dump drift

terraform show >before
terraform refresh
terraform show >after

diff -u before after Prevent auto-destroy:

 lifecycle {
    prevent_destroy = true
 }
Remote Exec
provisioner "remote-exec" {
    inline = [
         "apt install wget",
         "wget https://example.com/something"
    ]
}
Heredoc
resource "aws_iam_policy" "mypolicy" {
   name = "mypolicy"
   policy = <<EOF
{
    "Version": "2020-07-01",
    "Statement": ...
}
EOF
}

Foreach

To create multiple resources use this construct

locals {
  settings = {
    "key1"  = { prop1 = "xxx", prop2 = false },
    "key2"   = { prop1 = "yyy", prop2 = true },
    [...]
  }
}

resource "myresourcetype" "map" {
  for_each      = local.settings

  name          = each.key
  prop1         = each.value.prop1
  prop2         = each.value.prop2
  prop3         = "some constant"
}

For further reading visit the following terraform site