Home > Software design >  Using regex and conditional expression at the same time in Terraform
Using regex and conditional expression at the same time in Terraform

Time:11-06

I want to write a conditional expression in Terraform something like this:

name = regex("p[1-9] ", my_input) ? "production" : "testing"  

However, this does not work because regex function:

  1. Returns the matching string rather than true/false
  2. If my_input does not match the pattern, an error is thrown

What is the correct way to achieve this in Terraform?

CodePudding user response:

You can use can like this:

name = can(regex("p[1-9] ", my_input)) ? "production" : "testing"

Here is a simple input/output example:

$ terraform console
> can(regex("p[1-9] ", "pab1")) ? "production" : "testing"
"testing"
> can(regex("p[1-9] ", "p123")) ? "production" : "testing"
"production"
>
  • Related