Skip to content

Instantly share code, notes, and snippets.

@gmirsky
Created October 18, 2024 18:22
Show Gist options
  • Select an option

  • Save gmirsky/266d1a99ab1ff1aa9f160581918f1b63 to your computer and use it in GitHub Desktop.

Select an option

Save gmirsky/266d1a99ab1ff1aa9f160581918f1b63 to your computer and use it in GitHub Desktop.
Terraform assert to validate a multi-level mapped object
terraform {
required_providers {
assert = {
source = "hashicorp/assert"
version = ">= 0.14.0"
}
}
}
#
provider "assert" {
# Configuration options
}
#
variable "computers" {
type = map(
object(
{
make = string,
model = string,
quantity = number
add_on_card = map(
object(
{
card_quantity = number
card_type = string
}
)
)
}
)
)
validation {
condition = alltrue(
[
for indexed_item in var.computers : true if provider::assert::lowercased(
indexed_item.make
)
]
)
error_message = "Make must be lowercased"
}
validation {
condition = alltrue(
[
for indexed_item in var.computers : true if provider::assert::uppercased(
indexed_item.model
)
]
)
error_message = "Model must be in upper case"
}
validation {
condition = alltrue(
[
for indexed_item in var.computers : true if provider::assert::between(
1,
9999,
indexed_item.quantity
)
]
)
error_message = "Quantity must be between 0 and 9,999."
}
validation {
condition = alltrue(
[
for indexed_item in var.computers : alltrue(
[
for subindexed_item in indexed_item.add_on_card : true if provider::assert::greater_or_equal(
1,
subindexed_item.card_quantity
)
]
)
]
)
error_message = "add_on_card must be greater than zero"
}
validation {
condition = alltrue(
[
for indexed_item in var.computers : alltrue(
[
for subindexed_item in indexed_item.add_on_card : true if provider::assert::contains(
[
"PCI",
"PCIE X1",
"PCIE X4",
"PCIE X8",
"PCIE X16"
],
subindexed_item.card_type
)
]
)
]
)
error_message = "add_on_card must be: 'PCI','PCIE X1','PCIE X4','PCIE X8','PCIE X16'"
}
default = {
computer1 = {
make = "bigiron",
model = "MONSTER",
quantity = 20
add_on_card = {
riser = {
card_quantity = 1,
card_type = "PCIE X8"
}
memory = {
card_quantity = 4,
card_type = "PCIE X16"
}
scsi = {
card_quantity = 1,
card_type = "PCI"
}
fiberchannel16gb = {
card_quantity = 1,
card_type = "PCI"
}
}
},
computer2 = {
make = "flybynight",
model = "SCAM-13",
quantity = 20
add_on_card = {
riser = {
card_quantity = 1,
card_type = "PCIE X4"
}
memory = {
card_quantity = 2,
card_type = "PCIE X8"
}
}
}
}
}
#
output "computers" {
value = var.computers
description = "Sample multi level object validation"
sensitive = false
}
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment