Skip to content

Instantly share code, notes, and snippets.

@gswallow
Last active April 6, 2023 14:49
Show Gist options
  • Save gswallow/c1c543664f0ba0ac9994c1d896cf2a89 to your computer and use it in GitHub Desktop.
Save gswallow/c1c543664f0ba0ac9994c1d896cf2a89 to your computer and use it in GitHub Desktop.
Git info for terraform states
terraform {
required_providers {
external = {
source = "hashicorp/external"
version = "~> 2"
}
}
}
data "external" "git_remote_url" {
program = ["sh", "-c", <<EOF
echo "" | sed \
&& url="$(git remote get-url origin | sed -E \
-e 's#((ssh|git|rsync|https?)://|git@)?#https://#' \
-e 's#:[0-9]+##' \
-e 's#[^@/]+@##' \
-e 's#:([^/])#/\1#' \
-e 's#:/([^/])#/\1#g' \
-e 's#/$##' || echo none)" \
|| url="$(git remote get-url origin)" \
; echo '{"repo": "'$url'"}'
EOF
]
}
data "external" "git_revision" {
program = ["sh", "-c", <<EOF
rev="$(git rev-parse --verify HEAD \
|| echo none)" \
; echo '{"rev": "'$rev'"}'
EOF
]
}
data "external" "git_branch" {
program = ["sh", "-c", <<EOF
branch="$(git symbolic-ref -q --short HEAD \
|| echo detached)" \
; echo '{"ref": "'$branch'"}'
EOF
]
}
locals {
git_remote_url = data.external.git_remote_url.result.repo
git_revision = data.external.git_revision.result.rev
git_branch = data.external.git_branch.result.ref
tags = merge({
"Git/repository_url" = local.git_remote_url
}, var.tags)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment