Terraform string manipulation to remove X elements

Viewed 30

I have several strings that I just want to get a subset of like so:

my-bucket-customer-staging-ie-app-data

my-bucket-customer2-longname-prod-uk-app-data

and I just need to get the customers name from the string, so with the above examples I'd be left with

customer

customer2-longname

There's probably a simple way of doing this with regex although I've failed miserably in my attempts.

I'm able to strip the first part of the string using

trimprefix("my-bucket-customer-staging-ie-app-data", "my-bucket-")

trimprefix("my-bucket-customer-longname-prod-uk-app-data", "my-bucket-")

resulting in

customer-staging-ie-app-data

customer-longname-prod-uk-app-data

However Terraform's trimsuffix won't work as there can be several different regions/environments used.

What I'd like to do is slice the string and ignore the last 4 elements, which should then return the customer name regardless of whether it contains an additional delimiter in it.

Something like this captures the customer, however fails for long customer names:

element(split("-",trimprefix("my-bucket-customer-staging-uk-app-data", "my-bucket-")), length(split("-",trimprefix("my-bucket-customer-staging-uk-app-data", "my-bucket-")))-5)

customer

and is also quite messy.

Is there a more obvious solution I'm missing

1 Answers

I believe it's what regex is for.

> try(one(regex("\\w*-\\w*-(\\w*(?:-\\w*)*)-\\w*-\\w*-\\w*-\\w*","my-bucket-customer-staging-ie-app-data")),"")
"customer"
> try(one(regex("\\w*-\\w*-(\\w*(?:-\\w*)*)-\\w*-\\w*-\\w*-\\w*","my-bucket-customer2-longname-prod-uk-app-data")),"")
"customer2-longname"
> try(one(regex("\\w*-\\w*-(\\w*(?:-\\w*)*)-\\w*-\\w*-\\w*-\\w*","my-bucket-customer2-longname-even-longer-prod-uk-app-data")),"")
"customer2-longname-even-longer"

Reference: https://www.terraform.io/language/functions/regex

Related