Terraform Variable File

Terraform Variable File

Hello Everyone

Welcome to CloudAffaire and this is Debjeet.

In the last blog post, we have discussed terraform variables.

https://cloudaffaire.com/terraform-variables/

In this blog post, we will discuss terraform variable file.

What is Terraform variable file?

Values for the input variables of a root module can be gathered in variable definition files and passed together using the -var-file=FILE option. For all files which match terraform.tfvars or *.auto.tfvars present in the current directory, Terraform automatically loads them to populate variables. If the file is located somewhere else, you can pass the path to the file using the -var-file flag. It is recommended to name such files with names ending in .tfvars.

Variable file demo:

#create a directory and get inside it
mkdir terraform && cd terraform

#create terraform.tfvars (all variables will be declared in this file and called in main.tf file)
vi terraform.tfvars
---------------
variable "aws_access_key" {
default = "<your_access_key>"
}
variable "aws_secret_key" {
default = "<your_secret_key>"
}
variable "vpc_cidr" {
default = "10.0.0.0/10"
}
variable "vpc_tag_name" { #variable type string
type = "string"
default = "myvpc"
}
variable "subnet_count" { #variable type integer
type = "string"
default = "2"
}
variable "subnet_public_ip" { #variable type boolean
type = "string"
default = "true"
}
variable "subnet_cidrs" { #variable type list
type = "list"
default = ["10.0.1.0/24","10.0.2.0/24"]
}
variable "region" { #variable type map
type = "map"
default = {
"Mumbai" = "ap-south-1"
"Singapore" = "ap-southeast-1"
"Sydney" = "ap-southeast-2"
}
}
---------------
:wq

#create main.tf
vi main.tf
---------------
provider "aws" {
access_key = "${var.aws_access_key}"
secret_key = "${var.aws_secret_key}"
region = "${var.region["Mumbai"]}" #get variable region value (ap-south-1)
}
resource "aws_vpc" "myvpc" {
cidr_block = "${var.vpc_cidr}"
tags {
Name = "${var.vpc_tag_name}" #get variable vpc_tag_name value (myvpc)
}
}
resource "aws_subnet" "myvpc_subnet" {
count = "${var.subnet_count}" #get variable subnet_count value (2)
vpc_id = "${aws_vpc.myvpc.id}"
cidr_block = "${element(var.subnet_cidrs, count.index)}" #get variable subnet_cidrs value (10.0.1.0/24 and 10.0.2.0/24)
map_public_ip_on_launch = "${var.subnet_public_ip}" #get variable subnet_public_ip value (true)
tags {
   Name = "myvpc_subnet_${count.index+1}"
  }
}
-------------
:wq

#format code
terraform fmt

#initialized terraform
terraform init

#create the resource
terraform apply

#Login to AWS console and check VPC, subnets

#destroy the resources
terraform destroy

#cleanup
cd .. && rm -rf terraform

Hope you have enjoyed this article. In the next blog post, we will discuss terraform data source.

To get more details on terraform, please refer below terraform documentation

https://www.terraform.io/docs/index.html

 

Leave a Reply

Close Menu