是否有一种有效的方法将验证逻辑应用于Terraform运行中使用的变量?具体来说,我想检查一些变量的长度和外壳。这些变量是在TFVARS文件,变量文件中声明的变量的组合,并在运行时通过Terraform收集。
谢谢。
自定义验证规则
- Terraform文档 - 输入变量 - 自定义验证规则
结果
故障案例
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."
}
}
执行
$ 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.
通过案例
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."
}
}
执行
$ 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.
其他人
或者,使用null_resource local-exec在shell脚本中实现逻辑,或使用外部提供商将变量发送到外部程序以验证?
这不是您当前可以直接与Terraform一起完成的事情,但是我发现只需在必要时将输入变量弄脏到所需的格式。
作为一个示例,aws_lb_target_group
资源采用了protocol
参数,该参数当前要求它被覆盖,而不是自动上壳的壳体,并像aws_lb_listener
资源一样抑制diff,例如为协议(甚至health_check
块中的protocol
(。/p>
为了解决此问题,我在创建资源时只使用upper
函数:
variable "protocol" {
default = "http"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_lb_target_group" "test" {
name = "tf-example-lb-tg"
port = 80
protocol = "${upper(var.protocol)}"
vpc_id = "${aws_vpc.main.id}"
}
至于检查长度时,我只是将东西缩为使它们的正确长度。我目前是为ALBS执行此操作的,因为该名称的最大长度为32,并且我有Gitlab CI为某些服务创建评论环境,这些服务是基于GIT分支名称的slug命名的,因此几乎无法控制使用的长度。
variable "environment" {}
variable "service_name" {}
variable "internal" {
default = true
}
resource "aws_lb" "load_balancer" {
name = "${substr(var.environment, 0, min(length(var.environment), 27 - length(var.service_name)))}-${var.service_name}-${var.internal ? "int" : "ext"}"
internal = "${var.internal}"
security_groups = ["${aws_security_group.load_balancer.id}"]
subnets = ["${data.aws_subnet_ids.selected.ids}"]
}
使用上述环境或服务名称的任何组合都会导致环境/服务名称对被修剪到27个字符,最多使我想指定的额外字符留出空间。
<</p>受到此对话的启发,并找到了以下现有的提供商:https://github.com/craigmonson/terraform-provider-validate