是否有一种有效的方法将验证逻辑应用于terraform运行中使用的变量? 具体来说,我想检查一些变量的长度和大小。变量是在tfvars文件中,variables.tf文件中声明的变量的组合,并在运行时通过terraform收集。
感谢。
答案 0 :(得分:2)
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脚本中实现逻辑,还是使用外部提供程序将变量发送到外部程序进行验证?
答案 1 :(得分:1)
目前您不能直接使用Terraform,但我发现如果需要,可以更容易地将输入变量修改为所需的格式。
作为一个例子,aws_lb_target_group
resource需要一个protocol
parameter,当前要求它是大写的而不是自动上层大小的东西,并像aws_lb_listener
资源那样为协议抑制差异(或者甚至是protocol
区块中的health_check
。
要解决此问题,我只需在创建资源时使用upper
function:
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}"
}
至于检查长度,我只是对事物进行子串,以使它们成为正确的长度。我目前为ALB执行此操作,因为名称的最大长度为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个字符,这为我想要指定的额外字符留出了空间。
答案 2 :(得分:0)
受此对话启发,找到了以下现有提供商: https://github.com/craigmonson/terraform-provider-validate