Skip to content

Allow negative negative indices in slice() #21793

@hamstah

Description

@hamstah

Current Terraform Version

Terraform v0.12.2

Use-cases

My use case is being able to replace a suffix in an AWS ARN for secrets manager
The arn has the following structure

arn:aws:secretsmanager:us-east-1:123456789012:secret:path/to/secret-name-<random chars>

I want to replace the last 6 chars with a wildcard.
Having the ability to use negative indices I could split the ARN on - then slice -1 as the end index to remove the last element, then concatenate with my wildcard.

This would allow editing of lists in place instead of having to compute the length to pass

Attempted Solutions

This works but is quite verbose and requires intermediate variables

locals {
  split_arn = split("-", aws_secretsmanager_secret.secret.id)
  arn_without_suffix = slice(local.split_arn, 0, length(local.split_arn)-1)
  wildcard_arn = join("-", concat(local.arn_without_suffix, ["??????"]))
}

We could transform it into a 1 liner by splitting twice (once for the value and once for the length) but that becomes unreadable.

Proposal

Allow negative indices for the end of the slice in the slice function

Then have a look for other similar functions that should support it and make it consistent, for example element().

With this change the example above can be simplified to

join("-", concat(slice(split("-", aws_secretsmanager_secret.secret.id), 0, -1), ["??????"]))

References

#16044
#15582

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions