Terraform Essentials: Using Input/Output Variables and Resource Attributes

In this blog, we will understand the input/output variables and resource attributes in the Terraform.

HCL Basics

  • The HCL file consists of Blocks and Arguments.

       <block> <parameter> {
           key1 = value1
           key2 = value2
       }
    
  • A block is defined within curly braces & it contains a set of arguments in a key-value pair.

  • In Terraform: A block contains information about the infrastructure platform & set of resources within that platform, that we want to create.

Basic command

  • terraform init: Terraform initializes the project & identifies the provider to be used for the target environment.

  • terraform plan: Terraform drafts a plan to get a preview of the changes.

  • terraform apply: It makes the necessary changes required on the target environment to bring it to the desired state.

Example: Create the local file using Terraform

config file: main.tf

resource "local_file" "testing" {
  filename = "/opt/test.txt"
  content = "This test is created by Terraform."
}

Here,
- Block-type: resource
- Resource-type: local_file, It provides two bits of info, local → provider & file → resource type
- Resource-name: testing
- filename & content are the arguments

Execute,
terraform init
terraform plan
terraform apply

Note: We can have multiple configuration files within the configuration directory, saying that the file should have a .tf extension.

Input variable

Input variables are used to make your configurations more flexible and reusable. They allow you to parameterize the values in your configuration files instead of hardcoding them.

Syntax:

variable "variable_name" {
  type        = <type>       # Optional, e.g., string, number, bool, list, map
  default     = <default>    # sets a default value
}

Types of Input Variables

  1. String: A single line of text.

     variable "environment" {
       type    = string
       default = "production"
     }
    
  2. Number: A numeric value, which can be an integer or a float.

     variable "length" {
       type    = number
       default = 1
     }
    
  3. Bool: A boolean value (true or false).

     variable "enable_monitoring" {
       type    = bool
       default = true
     }
    
  4. List: A sequence of values of the same type and can have duplicate elements.

     variable "salutation" {
       type = list
       default = ["Mr", "Mrs", "Sir", "Maam"]
     }
    

    We can also define the type of element in the list, it could be string, number, or bool.

     variable "salutation" {
       type = list(string)
       default = ["Mr", "Mrs", "Sir", "Maam"]
     }
    
  5. Set: A sequence of values of the same type, but no duplicate element.

     variable "length" {
       type    = set(number)
       default = [1, 2, 5]
     }
    
  6. Map: A collection of key-value pairs, where keys are strings, and values can be any type.

     variable "content" {
       type = map(string)
       default = {
         "stat1" = "Hello world"
         "stat2" = "How are you"
       }
     }
    
  7. Object: A custom structure with named attributes of specific types.

     variable "car_config" {
       type = object({
         make      = string
         model     = string
         year      = number
         hybrid    = bool
         features  = list(string)
       })
       default = {
         make      = "Toyota"
         model     = "Camry"
         year      = 2023
         hybrid    = true
         features  = ["Sunroof", "Bluetooth", "Backup Camera"]
       }
     }
    
  8. Tuple: A sequence of values of different types.

     variable "car_details" {
       type = tuple([string, number, bool]) # Car name, manufacturing year, and hybrid status
       default = ["Toyota", 2023, true]
     }
    

Example: Use a different input variable and create the local file using Terraform.

Config file: main.tf, variable.tf

git clone https://github.com/minex970/terraform-overview/
cd basic
terraform init
terraform plan
terraform apply

Verify:

-rwxr-xr-x  1 root root   97 Dec  1 19:13 car-1.txt
-rwxr-xr-x  1 root root   82 Dec  1 19:13 car-2.txt
-rwxr-xr-x  1 root root   87 Dec  1 19:26 car-3.txt

Resource attributes

The attributes refer to the properties or outputs of a resource that can be accessed by other resources, variables, outputs, or modules. These attributes allow you to connect resources and pass information between them, enabling dynamic configurations.

# Using resource attributes in the resource block
resource "random_pet" "my_pet" {
  prefix = "Mr"
  separator = "."
  length = 1
}

resource "local_file" "pet" {
  filename = "/opt/pets.txt"
  content = "My favorite pet is ${random_pet.my_pet.id} \n"
}

Here, we use the following expression to get the output of the my_pet resource name and use them in the pet resource name.
${random_pet.my_pet.id}, this expression is also known as an interpolation sequence.

Output variable

  • Like the input variable, Terraform also supports the Output variable.

  • This is used to store the output of any resource or say the attributes of that, into an output variable.

Example: Use output variable to store the value of resource attribute.

output "pet-name" {
  value = random_pet.my_pet.id
}

Command: terraform output, to list the value of all output variables w/o running terraform apply command.

Github URL: https://github.com/minex970/terraform-overview/tree/master/basic