
Below are notes I took a few months ago when doing a Udemy Terraform course. I may update them over time as I learn more.
Plan
Plan is used to preview changes to the infrastructure.
Use: terraform plan
for output stdin, or in practice teraform plan -out <file>
The file is used in apply.
Apply
Makes changes to the infrastructure.
Destroy
Removes all infrastucture defined in plan files. Be careful in production!
Terraform keeps the remote state of the infrastructure.
It stores it in a file called terraform.tfstate
. There’s also a backup of the previous state (.backup).
If you run terraform apply after terminating an instance (or any defined node etc.) manually, Terraform will re-create it if it is part of the configuration.
The state file can be put into version control to see history of the infrastructure (JSON file). Allows for collaboration (beware of conflicts).
Large projects require storage of state in a remote repository.
Best not to have giant state files.
Remote Storage
This is called the backend.
- S3
- Consul
- Terraform enterprise
Benefits
- Allows for collaboration, always available to the whole team.
- Sensitive information is not stored locally.
- Enhanced backends allow for remote operations.
- Avoid having to push the terraform.tfstate to version control.
Cautions
- Not all remote stores support locking. S3 and Consul do.
Example Configuration
terraform {
backend "s3" {
bucket = "bucket"
key = "terraform/myproject"
region = "us-west-1"
}
}
You can also specify a read-only remote store directly in .tf
files. These are called a datasource.
Terraform variables were completely re-worked in 0.12 release.
Simple Types
Complex Types
- List
- Set
- Map
- Object
- Tuple
List
Lists are always ordered.
Referencing: myvar[0]
index number
Set
Like a list, but always unique values and does not maintain order, ie. [5,1,2,2,5] == [1,2,5]
Map
Like a dictionary (key/value).
Referencing: myvar['key']
Object
Like a map, but each element can have a different type. First is string, second is number.
{
firstname = "Bob"
housenumber = 100
}
Tuple
Like a list, but each element can have a different type. First is string, second is boolean, third is number.
ie. ["test", false, 0]
Other Variable Notes
- Variables that are declared in
vars.tf
but not defined will need to be defined in the terraform.tfvars
file.
- Best practice to NOT commit .tfvars files to repositories.