Terraform

Introduction

Hello. This is my terraform cheat sheet for me to easily refer to.

Over time I will append links to official documentation. If something does not look right, please reach out.


terraform init

Initializes terraform by downloading required plugins defined in .tf file

terraform init

Initializes terraform and skips downloading required plug ins

terraform init -get-plugins=false

terraform plan

For a fresh start, download the files as a zip and

terraform plan

terraform apply

Creates an execution plan through which you can preview infrastructure changes. Compares it to the prior state

terraform apply -auto-approve

terraform destroy

Tear down all managed resources and infrastructure

terraform destroy

You can also run apply command but with -destroy flag,

terraform apply -destroy

terraform fmt

Formats the code in all .tf files as per HCL standards

terraform fmt

terraform validate

Validates code in all .tf files in terms of syntax/correctness

terraform validate

terraform import

Used to add existing resources to the state file for management by terraform. Avoid usage.

terraform import <resource_type>.<resource_name> <resource_id>

terraform output

Lists all outputs from the session. Add -json flag for JSON format

terraform output && terraform output -json

terraform refresh

Reads current settings from managed resources and updates Terraform state file

terraform refresh

#Carries out the same action as below code
terraform apply -refresh-only -auto-approve

terraform state

Lists out all the resources currently tracked by the state file

terraform state list

Allows you to view the attributes of a single resource in the state file

terraform state show <resource>

Stops tracking a resource present in the state file

terraform state rm  aws_instance.myinstance

other commands

Check current version and update

terraform version && terraform get -update=true 

Notes

Sections of a .tf terraform file

  1. Provider - References the cloud service or other provider - Has optional version info

  2. Data - References to exisitng resources

  3. Resource - Resources managed by terraform

Types of terraform files

  1. main.tf file

  2. .tfvars file - Allows for seperation of environment specific values - That way the main.tf can be version controlled and reused in various env - Can be set as part of environment - Specify default values, if none then user is prompted - commandline flag takes precedence, then tf files , then env variable, then default variables.tf, then lastly prompt

  3. output file - Consists of data and messages to be displayed after terraform apply command. Can also be queried using terraform output

  4. .tfstate file - Is managed by terraform and consists of a snapshot of managed infrastructure and configuration.

Credits

Brilliant Youtube lesson by John Savill, here. Official Terraform Documentation, here.