Input Variables

About Input Variables

  • Terraform offers input variables
  • they are called "variables", but in fact these are parameters delivered to the current terraform module
  • Variables are declared in a variable section, and they are parsed before other tf sections.
  • Variables cannot reference other variables
  • Variables allow default values
  • They can specify a type, e.g:
    • list
    • map
    • string
  • You can define values for variables using:
    • cli (when planning or applying)
    • using environment variables

Some Variable Examples

Some examples:

  • A variable with a type of list(string), and a default value
1variable "availability_zone_names" {
2  type    = list(string)
3  default = ["us-west-1a"]
4}
  • A complex example, of a list of docker-ports. Each port has internal and external numeric values and a protocol (whici is a string):
 1variable "docker_ports" {
 2  type = list(object({
 3    internal = number
 4    external = number
 5    protocol = string
 6  }))
 7  default = [
 8    {
 9      internal = 8300
10      external = 8300
11      protocol = "tcp"
12    }
13  ]
14}

Using Input Variable Values

  • Here's how you use a variable in a resource:
1resource "aws_instance" "example" {
2  instance_type = "t2.micro"
3  ami           = var.image_id
4}

Assigning values in a .tfvars file

  • To set lots of variables, it is more convenient to specify their values in a variable definitions file (with a filename ending in either .tfvars or .tfvars.json) and then specify that file on the command line with -var-file:
1terraform apply -var-file="testing.tfvars"
  • A variable definitions file uses the same basic syntax as Terraform language files, but consists only of variable name assignments:
1image_id = "ami-abc123"
2availability_zone_names = [
3  "us-east-1a",
4  "us-west-1c",
5]