Terraform CLI Tutorials Flashcards
Terraform Variables vs Conventional Programming Language Variables
Terraform’s input variables don’t change values during a Terraform run such as plan, apply, or destroy.
Instead, they allow users to more safely customize their infrastructure by assigning different values to the variables before execution begins.
Terraform Variables can be defined where…
Anywhere in a configuration file (not recommended)
In separate variables.tf file (recommended)
A Variable Blocks three optional args
Description: A short description to document the purpose of the variable.
Type: The type of data contained in the variable.
Default: The default value.
e.g.,
variable "aws_region" { description = "AWS region" type = string default = "us-west-2" }
Referencing a variable in Terraform configuration file
var. variable_name
e. g.,
provider “aws” {
region = var.aws_region
}
Terraform simple variable types
string, int, bool
Terraform collection variable types
List: A sequence of values of the same type.
Map: A lookup table, matching keys to values, all of the same type.
Set: An unordered collection of unique values, all of the same type.
Defining a List Type variable
e.g.,
variable "public_subnet_cidr_blocks" { description = "Available cidr blocks for public subnets." type = list(string) default = [ "10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24", "10.0.4.0/24", "10.0.5.0/24", "10.0.6.0/24", "10.0.7.0/24", "10.0.8.0/24", ] }
Accessing multiple items in a list
slice() function
slice(list_object, start_index, end_index)
[‘a’, ‘b’] = slice([‘a’, ‘b’, ‘c’, ‘d’], 0, 2)
Defining a Map Type variable
map(Type)
e.g. map(string) -> a map of strings. Keys are always strings.
Note: A map is like a python dict
You will be prompted to assign a value to variable if…
there is no default value defined
Variable string interpolation
“The value of the variable is ${var.var_name}”
Variable string interpolation
“The value of the variable is ${var.var_name}”
Variable validation
Use a validation block within the variable block to perform validation on the values provided for a variable.
Validation block contains a condition and an error message (string)
variable "example"{ ... ... validation{ condition = length(var.example) < 10 error_message = "Example is too long" }
}
terraform init
Command to initialize your terraform configuration.
Terraform lock file
.terraform.lock.hcl
A file that records the versions and hashes of the providers used in this run. It ensures consistent Terraform runs in different environments.
.terraform directory
an artifact of terraform init
Stores the providers and modules defined in the project.
terraform plan
provides a preview of the actions Terraform would take to modify your infrastructure.