DEV Community

drewmullen
drewmullen

Posted on

Terraform - take a slice of a list

Say you have an s3 bucket with an unknown depth:

s3://<bucketname>/dir1/dir2/dirn...

say you wanted to output everything after the bucket:

dir1/dir2/dirn/

Theres no easy way to do this in terraform. Here is how you can do it. First determine the length of the string:

locals {
   arn_length = length(split("/", "s3://bucket-name/dir1/dir2/dirn/"))
...
Enter fullscreen mode Exit fullscreen mode

next use the length to slice and then rejoin the string (goes in the locals block mentioned above):

  bucket_depth = join("/", slice(split("/", "s3://bucket-name/dir1/dir2/dirn/"), 3, local.arn_length))
}
Enter fullscreen mode Exit fullscreen mode

voila!

try it out!

echo 'join("/", slice(split("/", "s3://bucket-name/dir1/dir2/dir3/"), 3, length(split("/", "s3://bucket-name/dir1/dir2/dir3/"))))' | terraform console
"dir1/dir2/dir3/"
Enter fullscreen mode Exit fullscreen mode

Discussion (0)