Terraform Input Variables Validation
Use Open Policy Agent (OPA) policies to validate Terraform input variables.
Introduction
When executing atmos terraform <sub-command>
commands, you can provide
Terraform input variables on the command line
using the -var
flag. These variables will override the variables configured in Atmos stack manifests.
For example:
Use double-dash --
to signify the end of the options for Atmos and the start
of the additional native arguments and flags for the Terraform commands.
Refer to Terraform CLI commands usage for more details.
Terraform processes variables in the following order of precedence (from highest to lowest):
-
Explicit
-var
flags: these variables have the highest priority and will override any other variable values, including those specified in--var-file
. -
Variables in
--var-file
: values in a variable file override default values set in the Terraform configuration. Atmos generates varfiles from stack configurations and provides it to Terraform using the--var-file
flag. -
Environment variables: variables set as environment variables using the
TF_VAR_
prefix. -
Default values in the Terraform configuration files: these have the lowest priority.
When log level Trace
is used, Atmos prints the Terraform variables specified on the command line in the "CLI variables" output.
For example:
Atmos exposes the Terraform variables passed on the command line in the tf_cli_vars
section, which can be used in
OPA policies for validation.
Terraform Variables Validation using OPA Policies
In atmos.yaml
, configure the schemas.opa
section:
atmos.yaml
In the component manifest, add the settings.validation
section to point to the OPA policy file:
stack.yaml
Require a Terraform variable to be specified on the command line
If you need to enforce that a Terraform variable must be specified on the command line (and not in Atmos stack manifests),
add the following OPA policy in the file stacks/schemas/opa/my-component/validate-my-component.rego
stacks/schemas/opa/my-component/validate-my-component.rego
When executing the following command (and not passing the name
variable on the command line), Atmos will validate
the component using the OPA policy, which will fail and prevent the component from being provisioned:
On the other hand, when passing the name
variable on the command line using the -var name=api
flag, the command will succeed:
Restrict a Terraform variable from being provided on the command line
If you need to prevent a Terraform variable from being passed (and overridden) on the command line,
add the following OPA policy in the file stacks/schemas/opa/my-component/validate-my-component.rego
stacks/schemas/opa/my-component/validate-my-component.rego
When executing the following command, Atmos will validate the component using the OPA policy, which will fail and prevent the component from being provisioned:
This command will pass the validation and succeed: