Skip to content

Instantly share code, notes, and snippets.

@mattmahn
Last active March 26, 2024 23:26
Show Gist options
  • Save mattmahn/f46420ba8d740cc008accfde964c2e74 to your computer and use it in GitHub Desktop.
Save mattmahn/f46420ba8d740cc008accfde964c2e74 to your computer and use it in GitHub Desktop.
Terraform: Get current Git commit SHA

This will return the full Git commit SHA of whichever branch is currently checkedout.

Dump the snippet into terraform console (run from within a Git repo) to see for yourself.

trimspace(file(".git/${trimspace(trimprefix(file(".git/HEAD"), "ref:"))}"))
@cfstras
Copy link

cfstras commented May 10, 2021

Note that this doesn't work when using a detached HEAD (for example, when running from a pipeline like GitLab CI).

What does work:

# get_sha.sh
#!/bin/bash
set -euo pipefail

echo '{"sha": "'"$(git rev-parse HEAD)"'"}'
data "external" "git_checkout" {
  program = ["${path.module}/get_sha.sh"]
}
// now use:
data.external.git_checkout.result.sha

@chm90
Copy link

chm90 commented Sep 2, 2021

I encountered an error relating to not finding the file. Fixed it with a chmod +x get_sha.sh

@chermed
Copy link

chermed commented Jun 17, 2022

@chm90 @cfstras you can improve the tf to

data "external" "git_checkout" {
  program = ["sh", "${path.module}/get_sha.sh"]
}
// now use:
data.external.git_checkout.result.sha

@wSedlacek
Copy link

This should use the git CLI without the external sh file

data "external" "git" {
  program = [
    "git",
    "log",
    "--pretty=format:{ \"sha\": \"%H\" }",
    "-1",
    "HEAD"
  ]
}

@joeshaw
Copy link

joeshaw commented Aug 30, 2023

If you are using Terraform Cloud or Terraform Enterprise you can use the TFC_CONFIGURATION_VERSION_GIT_COMMIT_SHA environment variable.

variable "TFC_CONFIGURATION_VERSION_GIT_COMMIT_SHA" {
  type = string
}

and reference it as vars.TFC_CONFIGURATION_VERSION_GIT_COMMIT_SHA

https://developer.hashicorp.com/terraform/cloud-docs/run/run-environment#environment-variables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment