hashicorp / terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
https://www.terraform.io/
Other
42.58k stars 9.54k forks source link

Substring | Trim character count from end of string #28669

Closed brendan-sherrin closed 3 years ago

brendan-sherrin commented 3 years ago

Current Terraform Version

Terraform v0.12.30
+ provider.archive v2.1.0
+ provider.aws v3.34.0
+ provider.local v2.1.0
+ provider.null v3.1.0

Use-cases

I'm using the below to generate names with some relation to the URL being checked for the AWS providers "aws_synthetics_canary" resource. To generate a name relating to the API endpoint being checked I trim the front of the URL until it hits the character count as the end of the URL is the part that changes betweend endpoints.

Attempted Solutions

I'm currently using "strrev(substr(strrev(STRING),0,21))" to swap the string around, trim characters from the swapped "end" of the string" then reverse the string again. This effectively trims characters from the back end of the URL string towards the front end.

Proposal

Either of the below would make life easier and my code nicer:

A reverse form of the substr command that selected a length of characters starting from the end of a string, instead of the beginning

substrrv (string, offset, length)

Alternatively adding a "length" version of the 3 related trim commands: trim, trimprefix, trimsuffix would accomplish the same end result

trimln (string, length) trimprefixln (string, length) trimsuffixln (string, length)

References

https://www.terraform.io/docs/language/functions/substr.html https://www.terraform.io/docs/language/functions/trim.html

jbardin commented 3 years ago

Hi @brendan-sherrin,

Thanks for filing the issue. You can also get a trailing substring relative to the length of the string itself.

substr(var.s, length(var.s)-21, length(var.s))

The substr function can actually do this a little more succinctly however with negative indexes, it just isn't currently shown in the Terraform documentation:

substr(var.s, -21, -1)
brendan-sherrin commented 3 years ago

Thanks @jbardin, that is really helpful

github-actions[bot] commented 3 years ago

I'm going to lock this issue because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues. If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.