Skip to content

Instantly share code, notes, and snippets.

@loganlinn
Last active October 28, 2021 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loganlinn/3f0c77bf1239c8c20425735fba5e2d62 to your computer and use it in GitHub Desktop.
Save loganlinn/3f0c77bf1239c8c20425735fba5e2d62 to your computer and use it in GitHub Desktop.
Shell setup for Gitlab-managed Terraform State
#!/bin/sh
# Shell setup for Gitlab-managed Terraform State
# Options
: "${GITLAB_TERRAFORM_STATE_NAME:=$(git rev-parse --show-prefix | sed -e 's/[^[:alnum:]]/-/g' | tr -s - | tr A-Z a-z | sed -e 's/-$//')}"
# Defaults for [GitLab CI/CD Predefined Variables](https://docs.gitlab.com/ee/ci/variables/predefined_variables.html)
: "${CI_PROJECT_PATH=$(git remote -v | awk '{print $2}' | sed -e 's;^git@gitlab.com:;;' -e 's;^https\?://gitlab\.com/;;' -e 's;\.git$;;' | head -n1)}"
: "${CI_PROJECT_ID="$(printf %s "$CI_PROJECT_PATH" | sed -e 's;/;%2F;g')"}"
: "${CI_API_V4_URL=https://gitlab.com/api/v4}"
: "${CI_PROJECT_TOKEN=${GITLAB_TOKEN-}}"
: "${GITLAB_USER_LOGIN=${GITLAB_USERNAME-}}"
# Environment variables for [http backend](https://www.terraform.io/docs/language/settings/backends/http.html#configuration-variables)
TF_HTTP_ADDRESS="$CI_API_V4_URL/projects/$CI_PROJECT_ID/terraform/state/$(printf %s "$GITLAB_TERRAFORM_STATE_NAME" | sed -e 's;/;%2F;g')" || true
export TF_HTTP_ADDRESS
export TF_HTTP_LOCK_METHOD=POST
export TF_HTTP_LOCK_ADDRESS=$TF_HTTP_ADDRESS/lock
export TF_HTTP_UNLOCK_METHOD=DELETE
export TF_HTTP_UNLOCK_ADDRESS=$TF_HTTP_ADDRESS/lock
export TF_HTTP_USERNAME=${TF_HTTP_USERNAME:-$GITLAB_USER_LOGIN}
export TF_HTTP_PASSWORD=${TF_HTTP_PASSWORD:-$CI_PROJECT_TOKEN}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment