Today marks the day 12 of 30 days of Terraform Challenge initiative by Piyush Sachdev. This blog is in continuation from previous blog of Day 11 - Terraform Functions of Part 1. In Part 1, we have discussed about String Functions, Numeric Functions, Collection Functions, Type Conversion, Date/Time Functions.
In this blog, we will discuss about remaining inbuilt Functions in terraform such as File Functions, Validation Functions and Lookup Functions.
Validation Functions:
In Terraform, you can define validation functions for variables to ensure that inputs confirm to your specific requirements. This is especially useful when you want to enforce constraints like valid string lengths, specific patterns, or predefined allowed values.
Validation blocks allow you to define strict rules for your variables. Instead of waiting for AWS to reject a resource creation (which takes time), Terraform can catch errors immediately during the plan phase.
Examples:
Example 1: Validating Instance Type
Let’s start by looking at a common validation scenario — checking the instance_type variable to ensure that only certain values are allowed. You might want to validate that the instance type name is between 2 and 10 characters and matches a specific pattern (e.g., t2 or t3 instances).
data "aws_ami" "validated_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_instance" "validated_instance" {
ami = data.aws_ami.validated_ami.id
instance_type = var.instance_type
tags = {
Name = "validated-instance"
Type = var.instance_type
}
}
variable "instance_type" {
default = "t2.micro"
validation {
condition = length(var.instance_type) >= 2 && length(var.instance_type) <= 20
error_message = "Instance type must be between 2 and 10 characters"
}
In the above example, you can see we have set a validation that Instance type length must be between 2 and 10 accomodating something like t2.micro, t3.micro such that, Not larger instance types will be allowed.
I have given a larger instance_type and it leads to below error.
terraform plan
data.aws_ami.validated_ami: Reading...
data.aws_ami.validated_ami: Read complete after 6s [id=ami-02610f36df0c59544]
Planning failed. Terraform encountered an error while generating this plan.
╷
│ Error: Invalid value for variable
│
│ on valid.tf line 19:
│ 19: variable "instance_type" {
│ ├────────────────
│ │ var.instance_type is "t2.micromediaughgfcghjfd"
│
│ Instance type must be between 2 and 20 characters
│
│ This was checked by the validation rule at valid.tf:22,3-13.
data "aws_ami" "validated_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
resource "aws_instance" "validated_instance" {
ami = data.aws_ami.validated_ami.id
instance_type = var.instance_type
tags = {
Name = "validated-instance"
Type = var.instance_type
}
}
variable "instance_type" {
default = "t2.micro"
validation {
condition = can(regex("^t[2-3]\\.", var.instance_type))
error_message = "Instance type must start with t2 or t3"
}
}
When I set instance_type as t4.large, then:
terraform plan
data.aws_ami.validated_ami: Reading...
data.aws_ami.validated_ami: Read complete after 5s [id=ami-02610f36df0c59544]
Planning failed. Terraform encountered an error while generating this plan.
╷
│ Error: Invalid value for variable
│
│ on valid.tf line 19:
│ 19: variable "instance_type" {
│ ├────────────────
│ │ var.instance_type is "t4.micro"
│
│ Instance type must start with t2 or t3
│
│ This was checked by the validation rule at valid.tf:27,3-13.
╵
Example 2: Validating String Suffix
Another common validation is checking if a string ends with a specific suffix, such as validating backup names.
variable "backup_name" {
default = "daily_backup"
validation {
condition = endswith(var.backup_name, "_backup")
error_message = "Backup name must end with '_backup'."
}
}
In the above example, you can see that when you give any value which are not ending with _backup, then it will leads to an error.
Sensitive Variables:
There were times where you will be giving a sensitive value to a terraform and you dont want that value to be displayed anywhere in the terraform console or needs to be stored in the terraform statefile, In those cases, you can add the parameter of "sensitive=true", which will not make that variable visisble to others in console after executing terraform apply.
variable "db_password" {
type = string
default = password
sensitive = true
}
output "db_pass_output" {
value = var.db_password
sensitive = true # By enabling here, the Output must also be marked sensitive
}
terraform plan
Changes to Outputs:
+ db_pass_output = (sensitive value)
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
If you didn't enable sensitive=true flag in output blog, then you will see like below:
terraform plan
╷
│ Error: Output refers to sensitive values
│
│ on main.tf line 7:
│ 7: output "db_pass_output" {
│
│ To reduce the risk of accidentally exporting sensitive data that was intended to be only internal, Terraform requires that any
│ root module output containing sensitive data be explicitly marked as sensitive, to confirm your intent.
│
│ If you do intend to export this data, annotate the output value as sensitive by adding the following argument:
│ sensitive = true

Top comments (0)