Skip to main content


Showing posts from July, 2022

Terraform accessing data from maps and list in the variable

In this post, we will discuss a use case where we want to access the variable value which is part of the list or the map. let’s try to understand the use case with an example: resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = <INSTANCE_TYPE> } variable "list" { type = list default = ["t2.nano", "t2.micro", "t2.medium"] } variable "types" { type = map default = { dev = "t2.nano", int = "t2.micro", prod = "t2.medium" }, } here we want to assign a value for the instance_type from either variable list or from variable types. Variable list is a list type and variable type is a map type. First, let’s use the list variable. To access the value from the list variable we will use the position. We want to assign let’s say t2.micro in that case we want position 1. resource "aws_instance&

Terraform different approaches for variable assignment.

In this post, we will discuss different approaches to variable assignment in Terraform. Here are the different approaches: Variable Defaults Command-line flags From a file Environment variables We will go into detail one by one and see examples of using them. 1. Variable Default In this approach, we create a file and define a variable and assign a default value to a variable. variable "instance_type" { default = "t2.micro" } This is referred to as variable default if no value is mentioned for the variable then the default value will be assigned. Here comes the question what will happen if we don’t provide a default value? Let’s try it out. We removed the default value and now our variable looks like this. variable "instance_type" {} And do a terraform plan terraform plan You will get an output like this: var.instance_type Enter a value: so if you have not defined a default variable terraform will ask you for the value from the command lin

Using Terraform Variables

Introduction Terraform variables are a central source from which values can be imported. In this way terraform variables are helpful in creating and managing centrally controlled reusable values. Let’s see how we can use the terraform variables to write clean code and avoid repetition using reusability. We are creating an AWS security group to demonstrate the variable's usage. resource "aws_security_group" "sg" { name = "demo-security-group" ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = [""] } ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = [""] } ingress { from_port = 53 to_port = 53 protocol = "tcp" cidr_blocks = [""] } } Take a not at cidr_blocks we are repeating t