Day 40 - Terraform Variables

Table of contents

🔹Variables and Outputs

  1. Input Variables: These are used to accept input values from users or from other modules. Input variables are typically defined in variable files (e.g., variables.tf) and can be set when calling a module or executing Terraform configurations. They allow users to customize the behavior of a module or configuration.

    Example:

     variable "filename" {
     default = "/home/ubuntu/terrform-tutorials/terraform-variables/demo-var.txt"
     }
     variable "content" {
     default = "This is coming from a variable which was updated"
     }
    

    Arguments:

    Terraform CLI defines the following optional arguments for variable declarations:

    • default - A default value which then makes the variable optional.

    • type - This argument specifies what value types are accepted for the variable.

    • description - This specifies the input variable's documentation.

    • validation - A block to define validation rules, usually in addition to type constraints.

    • sensitive - Limits Terraform UI output when the variable is used in configuration.

    • nullable - Specify if the variable can be null within the module.

Default values:

The variable declaration can also include a default argument. If present, the variable is considered to be optional and the default value will be used if no value is set when calling the module or running Terraform. The default argument requires a literal value and cannot reference other objects in the configuration.

Type Constraints:

The type argument in a variable block allows you to restrict the type of value that will be accepted as the value for a variable. If no type constraint is set then a value of any type is accepted.

While type constraints are optional, we recommend specifying them; they can serve as helpful reminders for users of the module, and they allow Terraform to return a helpful error message if the wrong type is used.

Type constraints are created from a mixture of type keywords and type constructors. The supported type keywords are:

The type constructors allow you to specify complex types such as collections:

  1. Output Value: These are used to export values from a module so that they can be used by other parts of the configuration or by other configurations that depend on the module. Output variables are defined in a module's outputs.tf file.

    Example:

     output "output_filename" {
       value = local_file.devops.filename
     }
    
     output "output_content" {
       value = local_file.devops.content
     }