We are decoding a json configuration file in our terraform main.tf within locals{}.
input_client_config = jsondecode(base64decode(local.client_config_base64))
Now we need to check for few parameters which must not exist in this json. If exist, throw dynamic error during planning stage. I tried below ways inside locals{} only. But these do not throw any error.
list_of_user =try(local.input_client_config.user,null)
or
list_of_user = can(local.input_client_config.user) ? "[ERROR] user list in client config should be empty." : "[Passed] user list in client config is empty."
Hi @dipanwita.saha,
It looks like you may be misunderstanding the try
and can
functions:
try
evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.
In your code for try
it will
- set
list_of_user = local.input_client_config
or, if that errors,
- set
list_of_user = null
can
evaluates the given expression and returns a boolean value indicating whether the expression produced a result without any errors.
In your code for can
it will
- set
list_of_user = "[ERROR] user..."
if there are NO errors accessing local.input_client_config
as can
returns true
where there are not errors
or,
- set
list_of_user = "[Passed] user..."
if there are errors accessing local.input_client_config
as can
returns false
where there are are errors.
As you can see, neither of these functions will actually raise an error. They are for returning values in a predicable way (as opposed to throwing an error) for use in assignments and checks.
What you likely need are Custom Conditions - Configuration Language | Terraform | HashiCorp Developer.
If the input_client_config
is passed in to the module at some point as a variable then this can be checked using input variable validation.
Alternatively you may be able to check using a precondition in a lifecycle block in an appropriate resource. However, these may not evaluate during plan if the value cannot be known before apply (See the above linked docs for details) so you may need some refactoring to ensure the value is known before the apply if this is an issue.
Thank you for the explanation. I have found the solution. First, used ‘can’ function on the specific variable of input_client_config. Then depending on return value (true or false) , created null resource.