Please list terraform variables and give examples of using
- User
Please list terraform variables and give examples of using
- Assistant
Please list terraform variables and give examples of using
In Terraform, variables are used to make configurations more flexible and reusable. They allow you to parameterize your Terraform configurations, making it easy to manage environments and infrastructure settings. You can define variables in a .tf file, typically named variables.tf, and then provide values for them in various ways, such as in a terraform.tfvars file, through environment variables, or via the command line.
Variables are defined using the variable block. Here are some examples of different types of variables:
String Variable
variable "aws_region" {
description = "The AWS region to deploy in"
type = string
default = "us-west-2"
}
Number Variable
variable "instance_count" {
description = "Number of instances to deploy"
type = number
default = 2
}
Boolean Variable
variable "enable_monitoring" {
description = "Enable monitoring for the instances"
type = bool
default = true
}
List Variable
variable "allowed_ips" {
description = "List of IP addresses allowed to access"
type = list(string)
default = ["192.168.1.1", "192.168.1.2"]
}
Map Variable
variable "tags" {
description = "Resource tags"
type = map(string)
default = {
"Environment" = "production"
"Project" = "my_project"
}
}
Variables can be used in your Terraform configuration like this:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
count = var.instance_count
tags = var.tags
}
terraform.tfvars File:
Create a terraform.tfvars file to specify values. For example:
aws_region = "us-east-1"
instance_count = 3
Command Line Flags:
You can specify values when running Terraform commands:
terraform apply -var="aws_region=us-east-1" -var="instance_count=3"
Environment Variables:
Export variables in your shell session:
export TF_VAR_aws_region="us-east-1"
export TF_VAR_instance_count=3
Terraform also supports variable files with any name, as long as they have a .tfvars or .tfvars.json extension. You can specify multiple variable files like this:
terraform apply -var-file="custom.tfvars"
By making use of variables, you can easily adapt your Terraform configurations to different environments and scenarios without changing the actual infrastructure code.
Not yet included in a published release.