I have a sting
crdemo01.australiaeast.data.azurecr.io
I want to build the following string from the above one:
crdemo01-test.australiaeast.data
The same logic should apply to the following input strings as well:
crdemo01.australiasoutheast.data.azurecr.io
crdemo01.azurecr.io
What I’m trying to achieve is to remove the .azurecr.io
part from the input string and append -test
to the first part of the remaining string.
How can I achieve this in Terraform?
3
Answers
Using replace twice with regex patterns:
There are a couple of functions that can help with this:
You can combine all that in one line, but is a nice visual to see the breakdown of the code.
This goal seems to require partitioning the input into three parts:
-test
added to it..azurecr.io
Here’s a regular expression pattern that should extract the first two segments as long as the third segment is present:
This uses named capture groups, so if you use it with Terraform’s
regex
function then you’ll obtain a map of strings with the keysfirst
andremain
, which correspond to the first and second segments I listed above.Using that pattern, you can achieve the result you described in two steps by first extracting the two relevant parts and then concatenating them back together in a slightly different way:
In the last case of
crdemo01.azurecr.io
theremain
result will benull
because there isn’t any intermediate part, so the conditional expression arranges to treat that as the empty string instead. (A possible variation would be to use(?P<remain>\..+|)
— a dot followed by other characters OR the empty string — which would then causeremain
to be""
when there’s no middle part.)Example results from the
regex
call fromterraform console
, in case it’s useful to see the intermediate results to understand what’s going on here: