如何为terraform schema.schema字段设置范围?

huangapple go评论138阅读模式
英文:

How to set range to terraform schema.schema field?

问题

在 schema.schema 中,我有一个 number_of_servers 字段,我需要对它设置一个范围。有没有办法做到这一点?

Schema: map[string]*schema.Schema{
    "number_of_servers": {
        Type:     schema.TypeString,
        Required: true,
        Range: 1-5,
    },
}
英文:

I have a number_of_servers field in schema.schema and I need to set a range to it. Is there any way to do it?

Schema: map[string]*schema.Schema{
		"number_of_servers": {
			Type:     schema.TypeString,
			Required: true,
            Range: 1-5,
		},

答案1

得分: 0

通常,验证函数用于验证任何配置(可能与变量结合)。这些函数作为terraform planterraform applyterraform destroy的一部分运行。用户还可以通过terraform validate显式触发验证,这在CI中常用。

假设"Range"是指限制给定字符串中字符的最小和最大数量,您可以使用验证包中的StringLenBetween函数。

Schema: map[string]*schema.Schema{
    "number_of_servers": {
        Type:     schema.TypeString,
        Required: true,
        ValidateFunc: validation.StringLenBetween(1, 5),
    },

您可以在以下实例中看到它的实际使用:
https://github.com/terraform-providers/terraform-provider-aws/blob/46bff11/aws/resource_aws_cloudwatch_event_target.go#L71-L75

英文:

Generally speaking validation functions are meant to validate any configs (possibly combined with variables). These run as part of terraform plan, terraform apply and terraform destroy. The user can also trigger explicit validation via terraform validate which is commonly used in CI.

Assuming that "Range" is meant to limit minimum & maximum number of characters in a given string you can use StringLenBetween from the validation package.

Schema: map[string]*schema.Schema{
    "number_of_servers": {
        Type:     schema.TypeString,
        Required: true,
        ValidateFunc: validation.StringLenBetween(1, 5),
    },

You can see it being used in practice here:
https://github.com/terraform-providers/terraform-provider-aws/blob/46bff11/aws/resource_aws_cloudwatch_event_target.go#L71-L75

huangapple
  • 本文由 发表于 2017年7月13日 02:11:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/45064827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定