DEV Community

drewmullen
drewmullen

Posted on • Edited on

1 2

Terraform: take a slice of a list with an unknown depth

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more