Related: HashiCorp
IaC definitions are defined in main.tf
Tip
Run
terraform fmt
andterraform validate
to format and validate the*.tf
files respectively.
Syntax
terraform
block
Defines the settings, and dependencies (a.k.a providers) needed for this project
resource
block
Defines the components of the infrastructure. Resource comes with two strings, the first being the type of the resource (defined by the provider
) and the second being the name of the resource. The combination of resource type and resource name forms a unique ID for a particular resource.
Resources have three sets of values:
Value Category | Notes |
---|---|
Arguments | Either required or optional. |
Attributes | Often assigned by the underlying cloud provider or API |
Meta-arguments | Changes the resource’s behaviour. This is a Terraform concept |
data
block
Similar to a resource, it is followed by two strings, with the first being the data provider. This block allows Terraform to get data from some external API.
Variables
Variables are typically defined in variables.tf
, as look as follows:
The variable can then be referred in main.tf
using var.instance_name
String interpolation can be done using "${var.instance_name}-suffix"
Outputs
Much like a state space representation, you can define outputs to inspect interesting states of your infrastructure
The value is the ID of the resource (<resource-type>.<resource-name
) and the attribute of that resource.
The output values are then displayed in the terminal when terraform apply
is run.
Modules
Reusable pieces of code callable by other code. Analogous to a library of functions.
Secrets
Can be specified using a .tfvars
file. This is similar to a .env
file that Terraform can read to load secrets required by Variables.
The format of the file is as follows:
# .tfvars
key1 = value1
key2 = value2
This can be read by a terraform command using the -var-file=secrets.tfvars
CLI flag.