Variable:
A variable helps to store data values.
Terraform supports multiple ways to use variables in configuration blocks.
Case1: Default values:
Variable “hello” {
Default = “t2.small”
}
“In above case we are declaring a variable “hello” and the default value is “t2.small” that refers to the instance vaule of the EC2 configuration code as shown below “
resource “aws_instance” “myec” {
ami = “ami-0a0ad6b70e61be944”
instance_type = “t2.large”
}
Case2: Passing multiple values
When we have multiple files we can pass variables through a file we need to store them in a file called “terraform.tfvars”
Example usage:
Variable “insttype” {}
Variable “amiid” {}
The values of the above variables should be stored in variables.tf file
amiid = “ami-0a0ad6b70e61be944”
insttype = “t2.large”
We have declared above variables.if we need to use them in source code the syntax is : VAR.varname
resource “aws_instance” “myec” {
ami = var.insttype
instance_type = var.amiid
}
When we do terraform apply the values will be associated to the code.
Case3:
Passing values through a file:
We can pass multiple variables through a file.the syntax to pass multiple variables through a file is :
Syntax
Terraform plan –var-file= “myfile.tfvars”
Here myfile consists of the variables and their associated values.
Example:
Instype= “t2.small”
amiid = “ami-0a0ad6b70e61be944”
Now to use these values in code
resource “aws_instance” “myec” {
ami = var.insttype
instance_type = var.amiid
}
Case 4:
Using envnvironment variables
Environment variables can be used to set variables. The environment variables must be in the format TF_VAR_name and this will be checked last for a value. For example:
export TF_VAR_region=ap-south -1
export TF_VAR_ami=ami-14dg56
Hope this document is very useful for you in decalring terraform variables
We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.
© 2021 TheTerraform.in - All Rights Reserved.
Designed By TenXinfotech.