How to use Terraform Variables

In software engineering we try to make code as modular as possible. Following the same footsteps we should try to make terraform as modular as possible.

One of the concept that is going to help is the notion of variables. Let say you want to have a service built and have it being served on a given port lets say 8080. Instead of sprinkling this port all over the place we can have a variable that stores the port and use that in our terraform code.

File based approach

Let's create a new file called variables.tf and add the code below

variable "aws_region" {
  description = "AWS region to launch servers."
  default     = "us-east-1"
}

variable "aws_amis" {
  default = {
    us-east-1 = "ami-0a5f4555ead581241",
    us-west-1 = "ami-06f157dbd9c69404b"
  }
}

variable "port" {
  default = 8080
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Once we have the code we can use the variables in building the actual infrastructure. Assuming we want to build a aws_security_group we can use the $ interpolation to get the value of a given variable.

resource "aws_security_group" "allow-http-traffic" {
  name = "allow-http-traffic"
  ingress {
    from_port = "${var.server_port}"
    to_port = "${var.server_port}"
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
1
2
3
4
5
6
7
8
9

Command Line

You can also pass there variable on the command line.

terraform apply -var server_port=8080 -var aws_region='us-east-1'
1

Environment Variables

You could also pass the variable using ENVIRONMENT variables. This is done by appending TF_VAR to the actual variable. example : TF_VAR_aws_region or TF_VAR_server_port.