Skip to main content
substr(str, offset, length) returns the portion of str starting at offset with at most length characters.

Signature

substr(str string, offset number, length number) string
offset is zero-based. A negative offset counts from the end of the string. Pass -1 for length to return everything from offset to the end of the string.

Example

Use the first 8 characters of a full commit SHA as a short identifier in Docker image tags:
variable "commit" {
  description = "Full git commit SHA"
  type        = string
}

computed "short_sha" {
  description = "Short commit identifier for image tagging"
  expression  = substr(var.commit, 0, 8)
}

task "build" {
  description = "Build and tag the image with the commit SHA"
  commands = [
    "docker build -t myapp:${computed.short_sha} .",
    "docker push myapp:${computed.short_sha}",
  ]
}
a3f9e21b4d6c8f12... becomes a3f9e21b.

Notes

  • offset and length count grapheme clusters, not bytes or code points.
  • If offset is beyond the end of the string, the result is an empty string.
  • If length exceeds the available characters from offset, the result is truncated to the string end.
  • Use length = -1 to extract from a position to the end: substr(str, 2, -1).