Skip to content

Instantly share code, notes, and snippets.

@sergsoares
Created July 14, 2022 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergsoares/c4e415a322245bcbefdb3ab651beb262 to your computer and use it in GitHub Desktop.
Save sergsoares/c4e415a322245bcbefdb3ab651beb262 to your computer and use it in GitHub Desktop.
Validation of complex variables in terraform
# terraform.vars
rules = [
{
api_groups = [""]
resources = ["pods","services","deployments","jobs"]
verbs = ["*"]
},
{
api_groups = [""]
resources = ["namespaces"]
verbs = ["get", "watch", "list"]
}
]
# variables.tf
variable "rules" {
type = list(object({
api_groups = list(string)
resources = list(string)
verbs = list(string)
}))
}
# main.tf
resource "kubernetes_cluster_role" "this" {
metadata {
name = "${var.app}"
labels = {
k8s-addon = "${var.app}.addons.k8s.io"
k8s-app = "${var.app}"
}
}
dynamic "rule" {
for_each = var.rules
content {
api_groups = rule.value["api_groups"]
resources = rule.value["resources"]
verbs = rule.value["verbs"]
}
}
}
@sergsoares
Copy link
Author

sergsoares commented Jul 14, 2022

If incorrect variables are provided:

 Error: Invalid value for input variable
│ 
│   on terraform.tfvars line 6:
│    6: rules = [
│    7:   {
│    8:     api_groups = [""]
│    9:     resources = ["pods","services","deployments","jobs"]
│   10:     verbs      = ["*"]
│   11:   },
│   12:   {
│   13:     api_groups = [""]
│   14:     resources = ["namespaces"]
│   15:     verb      = ["get", "watch", "list"]
│   16:   }
│   17: ]
│ 
│ The given value is not valid for variable "rules": element 1: attribute "verbs" is required.
╵
╷
│ Error: Incorrect variable type
│ 
│   on variables.tf line 17:
│   17: variable "rules" {
│ 
│ The resolved value of variable "rules" is not appropriate: element 1: attribute "verbs" is required

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment