问题
I'm creating a plugin in Terraform and I want to add a field to the schema which can be called only when another field has been provided.
"host_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("host_name", nil),
Description: "Should give name in FQDN if being used for DNS puposes .",
},
"enableDns": &schema.Schema{
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("host_name", nil),
Description: "Should give name in FQDN if being used for DNS puposes .",
Here I want to pass the enableDns
string in the .tf
file only when host_name
is passed. If it is not given and I pass enableDns
it should throw an error during plan.
回答1:
Terraform providers don't really have a first class way to do stuff conditionally based on other parameters other than the ConflictsWith
attribute.
There is a hacky way to do some cross parameter stuff using CustomizeDiff
but it's only really used in a couple of places where it's really needed.
Normally the provider would simply validate the individual parameters and if the API that the provider is working against requires cross parameter validation then this is only seen at apply time when the API returns the error.
For an example of using CustomizeDiff
to throw a plan time error when doing cross parameter validation see the aws_elasticache_cluster resource:
CustomizeDiff: customdiff.Sequence(
func(diff *schema.ResourceDiff, v interface{}) error {
// Plan time validation for az_mode
// InvalidParameterCombination: Must specify at least two cache nodes in order to specify AZ Mode of 'cross-az'.
if v, ok := diff.GetOk("az_mode"); !ok || v.(string) != elasticache.AZModeCrossAz {
return nil
}
if v, ok := diff.GetOk("num_cache_nodes"); !ok || v.(int) != 1 {
return nil
}
return errors.New(`az_mode "cross-az" is not supported with num_cache_nodes = 1`)
},
来源:https://stackoverflow.com/questions/53955348/make-a-resource-schema-dependant-on-another-variable