Terraform Variables

Terraform Variables

Day 63 of #90DaysOfDevOps

What are terraform variables?

  • Terraform variable are important part of the terraform as it holds values of name of instance, configs etc.

  • All the variables can be stored in a variables.tf file and can be accessed by var object in main.tf file in terraform.

example:

variable "filename" {
    default = "/home/ubuntu/terraform-practice/devops-test.txt" 
}
variable "content" {
    default = "This is coming from a variable"
}

Task-01

  • Create a local file using Terraform

Data Types in Terraform

Map

variable "file_contents" {
    type = map
    default = {
        "statement1" = "this is cool"
        "statement2" = "this is cooler"
    }
}

Task-02

  • Use terraform to demonstrate usage of List, Set and Object datatypes

  • Use terraform refresh - to refresh the state by your configuration file, reloads the variables


Task 1

Create a local file using Terraform:

create a file and write code to create variable:

In main file access to the variables with var object

Write terraform init and then terraform apply

Verify the output file

Map in terraform:

  • In Terraform, a “map” is a data structure used to represent a collection of key-value pairs. It is similar to an object or dictionary in other programming languages.

  • Map created with type = map.

  • The keys has to be unique in key-value pairs.

Example:

variable "content_map" {
  type = map(any)
  default = {
    "statement1" = "this is cool"
    "statement2" = "this is cooler"
  }
}

Access the variables with var.content_map["key"] in the content.

terraform apply

Verify the output files:


Task 2

Data Types:

List:

  • A sequence of values identified by consecutive whole numbers starting with zero.

    The keyword list is a shorthand for list(any), which accepts any element type as long as every element is the same type.

  • Duplicate values are accepted.

Set:

  • A collection of unique values that do not have any secondary identifiers or ordering.

Object:

  • a collection of named attributes that each have their own type.

  • The schema for object types is a pair of curly braces containing a comma-separated series of pairs. Values that match the object type must contain all of the specified keys, and the value for each key must match its specified type. (Values with additional keys can still match an object type, but the extra attributes are discarded during type conversion.)

Terraform refresh:

terraform refresh is a Terraform command that retrieves the current state of the resources defined in your configuration and updates the Terraform state file to match that state.


Refer more: https://developer.hashicorp.com/terraform/language/expressions/type-constraints

Thank you for reading!