Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient variable validation with Terraform

Tags:

terraform

hcl

Is there an efficient way to apply validation logic to variables used in a terraform run? Specifically I want to check the length and casing of some variables. The variables are a combination of ones declared in tfvars files, in variables.tf files, and collected during runtime by terraform.

Thanks.

like image 260
Bob Avatar asked Oct 17 '22 19:10

Bob


1 Answers

Custom Validation Rules

  • Terraform document - Input Variables - Custom Validation Rules

Results

Failure case

provider aws {
     profile="default"
}
terraform {
  experiments = [variable_validation]
}

## Custom Validation Rules
variable "test" {
  type        = string
  description = "Example to test the case and length of the variable"
  default = "TEsT"

  validation {
    condition     = length(var.test) > 4 && upper(var.test) == var.test
    error_message = "Validation condition of the test variable did not meet."
  }
}

Execution

$ terraform plan

Warning: Experimental feature "variable_validation" is active

  on main.tf line 5, in terraform:
   5:   experiments = [variable_validation]

Experimental features are subject to breaking changes in future minor or patch
releases, based on feedback.

If you have feedback on the design of this feature, please open a GitHub issue
to discuss it.


Error: Invalid value for variable   # <---------------------------

  on main.tf line 9:
   9: variable "test" {

Validation condition of the test variable did not meet.

This was checked by the validation rule at main.tf:14,3-13.

Pass case

terraform {
  experiments = [variable_validation]
}

## Custom Validation Rules
variable "test" {
  type        = string
  description = "Example to test the case and length of the variable"
  default = "TESTED"

  validation {
    condition     = length(var.test) > 4 && upper(var.test) == var.test
    error_message = "Validation condition of the test variable did not meet."
  }
}

Execution

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

Others

Alternatively, use null_resource local-exec to implement logic in shell script, or use external provider to send the variable to an external program to validate?

like image 135
mon Avatar answered Oct 21 '22 05:10

mon