Day 63 - Terraform Variables

Day 63 - Terraform Variables

variables in Terraform are quite important, as you need to hold values of names of instance, configs , etc.

We can create a variables.tf file which will hold all the variables.

The variable declaration can optionally include three arguments:

  • description: briefly explain the purpose of the variable and what kind of value is expected.

  • type: specifies the type of value such as string, number, bool, map, list, etc.

  • default: If present, the variable is considered to be optional and if no value is set, the default value is used.

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

These variables can be accessed by var object in main.tf

Task-01

  • Create a local file using Terraform Hint:

resource "local_file" "devops" {
filename = var.filename
content = var.content
}

Local file creation from main.tf

Local file creation with variables:

variable.tf

main.tf

output:

Data Types in Terraform

  1. Map: A map is a collection of values where each value is identified by a string label.
    In the example below is a map variable named managed_disk_type to define the type of storage we want to use based on the region in Azure. In the default block, there are two string values, “Premium_LRS” and “Standard_LRS” with a named label to identify each one westus2 and eastus.

    map variable define

    1. Type 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

  • Put proper screenshots of the outputs

Use terraform refresh

To refresh the state by your configuration file, reloads the variables

Datatype:List

List: A Terraform list variable is a sequence of similar values indexed by numbers (starting with 0). It accepts any type of value as long as they are all of the same types. Lists can be defined either implicitly or explicitly.

Type:Object

  1. Object: An object is a structural type that can contain different types of values, unlike map, list. It is a collection of named attributes that each have their own type.
    In the below example, we have declared an object type variable os for the os image that can be used to deploy a VM.

  2. Objects, similar to maps, can represent key-value pairs. Objects have additional functionality that allow them to be used as a data structure. Objects are defined using curly braces {} and the . operator is used to access object properties.

    object variable define

github:https://github.com/gsbarure/Terraform.git

linkdin:https://www.linkedin.com/in/gajanan-barure-7351a4140

Happy Learning :)

Thank you for reading!! Hope you find this helpful.

#day63#90daysofdevops#devopscommunity#

Shubham Londhe