VSChina / magic-modules

Magic Modules: Automagically generate Google Cloud Platform support for OSS
Apache License 2.0
1 stars 4 forks source link

How to customize the validation functions in schema? #44

Closed houkms closed 4 years ago

houkms commented 4 years ago

A good example is here in BatchAccount.

Firstly, specify the validation function name in properties. Secondly, include the function's erb file path in custom_code.

properties:
  name: !ruby/object:Overrides::Terraform::PropertyOverride
    validation: !ruby/object:Provider::Terraform::Validation
      function: validateAzureRMBatchAccountName
custom_code: !ruby/object:Provider::Azure::Terraform::CustomCode
  extra_functions: ./terraform_extra_functions.erb
// file name: terraform_extra_functions.erb
func validateAzureRMBatchAccountName(v interface{}, k string) (warnings []string, errors []error) {
    value := v.(string)
    if !regexp.MustCompile(`^[a-z0-9]+$`).MatchString(value) {
        errors = append(errors, fmt.Errorf("letters and numbers only are allowed in %q: %q", k, value))
    }

    if 3 > len(value) {
        errors = append(errors, fmt.Errorf("%q cannot be less than 3 characters: %q", k, value))
    }

    if len(value) > 24 {
        errors = append(errors, fmt.Errorf("%q cannot be longer than 24: %q %d", k, value, len(value)))
    }

    return warnings, errors
}