Search code examples
terraformgoogle-cloud-sqlterraform-provider-gcp

Conditionally ignore parameter in Terraform if its value is not provided?


I am using "google_sql_database_instance" resource to create a cloud instance with private IP only and taking the value for _private_network_ from variables file or command line argument or no value provided at all.

All I am trying to achieve is, create private IP instance only if private_network is provided and include _private_network_ parameter only if its value is provided. The problem here is this variable doesn't accept empty string ("") as it validates the bellow regular expression.
"projects/((?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)))/global/networks/((?:[a-z](?:[-a-z0-9]*[a-z0-9])?))$".

How would I make a module which is configurable (create private IP instance only if private_network is provided otherwise ignore the parameter completely) and does not compulsorily asks for the value of _private_network_ variable?


Solution

  • The old approach to this would be to pass an empty string ("") to the parameter and the provider would ignore it by convention.

    Unfortunately this isn't done everywhere across all providers yet so if you are unable to pass an empty string due to validation on the parameter then you're stuck for now.

    The options you have are to raise a pull request for the provider allowing you to pass an empty string, create a second module that differs only by whether it has a private network, or wait for Terraform 0.12 which will introduce the null value that will then make Terraform core ignore the parameter entirely.

    The last option is the best one in my opinion but if you have an urgent need (currently no expected release date for 0.12 other than when it's ready) then I'd split the module into two for now to get you able to achieve this and then you can drop the private clone of the module and use the null value when 0.12 is released and you have upgraded to it.