Add validation to TerraformVariable in typescript

I have a TerraformVariable and want to add validation using TS.

    const capacity = new TerraformVariable(this, 'Capacity', {
      type: 'number',
      default: 2,
      description: 'The initial number of instances'
    });
    capacity.addValidation({
        condition: capacity.numberValue >= 1 && capacity.numberValue <= 5,
        errorMessage: 'Must be between 1 and 5 EC2 instances'
    });

But I receive an error saying:

Error: Invalid variable validation condition
 "The condition for variable "Capacity" must refer to var.Capacity in order to test incoming values."

If I do as the error says

    capacity.addValidation({
        condition: 'var.Capacity >= 1 && var.Capacity <= 5'
        errorMessage: 'Must be between 1 and 5 EC2 instances'
    });

I get the same issue.

I’ve got similar errors if I want to add regular expression as a condition:

stringVar.addValidation({
      condition: `${Fn.regex("arn:aws:secretsmanager:.*", stringVar.stringValue)}`,
      errorMessage: 'Must follow SecretsManager ARN syntax'
    })

Can someone help me with the correct syntax? I also couldn’t find any example that uses these validations.

Hi @bmaidics,

I’m not totally sure what’s going on here but I notice that your typescript variable is called “variable” (lowercase) while the Terraform variable name is “Variable” (uppercase V).

Changing the Terraform variable name to lowercase would at least make the two consistent, and make this better match idiomatic Terraform naming conventions.

The fact that even writing the condition using uppercase V didn’t work suggests that something else might be going on too, but perhaps we can try making the names consistent first and then at least it hopefully leads to a more intuitive error message.