Skip to content

Variables

variables.tf file will usually hold every single variable in your Terraform project.

Its idea is to have a centralized place to store all the variables which makes configuration of the Terraform project more DRY.

For modules, a variables.tf also acts as the place to document all the inputs to the module.

Variables can be string, list(<type>), map(<type>), number, bool or even null

You can refer to your variables with the prefix of var. i.e. var.name inside the module.

Create your variables.tf file and introduce some variables needed for this exercise.

A variable is created by defining a variable block, which has a name, and then the parameters type and description. You can also specify a default.

Exercises

  1. Create your first variable "name"
    • Type is string
    • Default is your combination of your first and lastname e.g. Matti Meikäläinen would be matmei
    • Description is Service name to be used in this project to determine what resource belongs to who
  2. Create a second variable called "project"
    • Type is string
    • Default is the Project ID, which you will get from your instructor.
    • Description Project ID
  3. Create a third variable called region
    • Type is string
    • Default is europe-north1
    • Description is GCP region
  4. Create a fourth variable called zone
    • Type is string
    • Default is europe-north1-b
    • Description is GCP zone

Usually, it's good to use descriptions to tell what the variable is to the users of your project or module.

Extra

  1. Make all or some of the variables required, by omitting the default values.
    • You can create a terraform.tfvars file, which contains the values or pass them in from the command line.
  2. Skip creating the project as a variable and instead use it as a data source
    • Since it is an existing resource, you can use a data source block such as data "google_project" "my_project" to fetch the ID in main.tf

Answer
variable "name" {
  type        = string
  default     = "matmei"
  description = "Service name to be used in this project to determine what resource belongs to who"
}

variable "zone" {
  type        = string
  default     = "europe-north1-b"
  description = "Zone to use"
}

variable "region" {
  type        = string
  default     = "europe-north1"
  description = "GCP region"
}

variable "project" {
  type        = string
  default     = "PROJECT_ID"
  description = "Project ID"
}
Hint

You can format code by running terraform fmt.

Next

Next, we create some actual resources for Cloud Run.