Starting code

Let's start by showing animals.tf.py from the previous pages, plus a new file users.tf.py. We can see that these files are hardcoding their data: the lists of animals and users.

# animals.tf.py

from pretf.api import block


def pretf_blocks():
    animals = ["dog", "cat", "buffalo", "rabbit", "badger"]  # hardcoded
    for name in animals:
        animal = yield block("resource", "random_integer", name, {
            "min": 1,
            "max": 10,
        })
        yield block("output", name, {"value": animal.result})
# users.tf.py

from pretf.api import tf


def pretf_blocks():
    users = ["ray", "violet"]  # hardcoded
    for name in users:
        yield block("resource", "aws_iam_user", "name", {
            "name": name,
        })

Terraform variables

Terraform variables can be accessed in Pretf by adding a var argument to the pretf_blocks() function. Pretf will see this argument in the function signature and pass in a variables object. Let's use that instead of hardcoding values:

# variables.tf

variable "animals" {
  type = list(string)
}

variable "users" {
  type = list(string)
}
# terraform.tfvars

animals = ["dog", "cat", "buffalo", "rabbit", "badger"]

users = ["ray", "violet"]
# animals.tf.py

from pretf.api import block


def pretf_blocks(var): # var added to the function signature
    for name in var.animals: # accessing a variable
        animal = yield block("resource", "random_integer", name, {
            "min": 1,
            "max": 10,
        })
        yield block("output", name, {
            "value": animal.result,
        })
# users.tf.py

from pretf.api import block


def pretf_blocks(var): # var added to the function signature
    for name in var.users: # accessing a variable
        yield block("resource", "aws_iam_user", name, {
            "name": name
        })

Variable definition precedence

From the Terraform documentation:

Terraform loads variables in the following order, with later sources taking precedence over earlier ones:

  • Environment variables.
  • The terraform.tfvars file, if present.
  • The terraform.tfvars.json file, if present.
  • Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
  • Any -var and -var-file options on the command line, in the order they are provided.

Pretf uses the same rules when resolving variable values.

If a project has *.tfvars.py files to generate *.tfvars.json files that would change the value of a variable (i.e. one of the above sources has already set the variable to a different value) then Pretf will exit with a descriptive error message. This ensures that Python and Terraform run with consistent variable values.