I can see this being useful in following situation:
resource "aws_subnet" "private" {
count = "${var.number_of_azs}"
vpc_id = "${aws_vpc.default.id}"
cidr_block = "${element(split(",", lookup(var.subnet_cidrs, "private")), count.index)}"
availability_zone = "${element(split(",", lookup(var.aws_avalability_zones, var.aws_region)), count.index)}"
tags {
Name = "${substr(-1, 1, element(split(",", lookup(var.aws_avalability_zones, var.aws_region)), count.index))}-private"
}
}
so the important bit:
${substr(-1, 1, element(split(",", lookup(var.aws_avalability_zones, var.aws_region)), count.index))}
if the element returns e.g. eu-west-1a then turns into a, which means I can get
tags {
Name = "a-private"
}
+1. My use case is explicit availability zone placement is several places using default values.
+1
+1
+1
+1
Solution I used if you need first character:
${format("%.1s", var.string)}
There's some other things you can do with the format of the string.
https://blog.golang.org/strings
and
https://golang.org/pkg/fmt/
Thank you for the suggestion @radeksimko – I'll bring this up internally and see if we can make it happen 😄
Do we have any updates here?
This isn't directly what this issue is about, but something similar to this is available as part of the aws_availability_zone data source. It exports separately the region and name_suffix attributes to allow (in @radeksimko's example) eu-west-1a to be split into eu-west-1 and a respectively, while simultaneously validating that the given AZ is valid by querying the AWS API.
I would like this feature as well to keep my code a bit cleaner. In the mean time here is how I'm doing substring to get just first 32 chars:
"${join("",slice(split("","reallylongstringherethatneedstobetrimmedtofirst32charsonly"),0,31))}"
Looks like this PR may explicitly solve this issue: https://github.com/hashicorp/terraform/pull/12870
@fillup your code saved my day, but I have to add that your example is not exactly doing what you state, it is generating a substring of the first 31 (and not 32) characters of the provided string, the second argument is end final index, exclusive. it should be:
"${join("",slice(split("","reallylongstringherethatneedstobetrimmedtofirst32charsonly"),0,32))}"
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.