Related: HashiCorp


IaC definitions are defined in main.tf

Tip

Run terraform fmt and terraform 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 CategoryNotes
ArgumentsEither required or optional.
AttributesOften assigned by the underlying cloud provider or API
Meta-argumentsChanges 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:

# variables.tf
 
variable "instance_name" {
  description = "..."
  type        = string
  default     = "..."
}

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

# outputs.tf
 
output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.app_server.id
}

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.

>>> terraform apply
aws_instance.app_server: Refreshing state... [id=i-0bf954919ed765de1]
 
Changes to Outputs:
  + instance_id        = "i-0bf954919ed765de1"
  + instance_public_ip = "54.186.202.254"

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.