Skip to content

Commit

Permalink
Dynamically locate remote state config (patch)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukiffer committed Jan 18, 2023
1 parent 517ed49 commit a72ad1c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
35 changes: 35 additions & 0 deletions .tools/find-remote-state-config.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bash

function check_path() {
local -r path="$1"
local -r max_depth="$2"
local i="$3"
local -r test_path="$path/.remote-state-config.yaml"

if [ -f "$test_path" ]; then
collapsed_path="$(readlink -f "$test_path")"
echo "- Remote state config found at $collapsed_path" 1>&2
echo "" 1>&2
echo "$collapsed_path"
exit 0
else
if ((i > max_depth)); then
exit 1
fi
((i += 1))
check_path "$path/.." "$max_depth" "$i"
fi
}

function main() {
local -r path="$1"
local -r separators="${path//[!\/]/}"
local -r depth="${#separators}"

echo "" 1>&2
echo -e '\033[1mLocating Terraform remote state config...\033[0m' 1>&2

check_path "$PWD" "$depth" 0
}

main "$@"
Empty file modified .tools/verify-tfc-workspace.sh
100644 → 100755
Empty file.
7 changes: 4 additions & 3 deletions terragrunt.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
# ---------------------------------------------------------------------------------------------------------------------

locals {
remote_state_config = yamldecode(file(".remote-state-config.yaml"))
workspace = replace(replace("${path_relative_to_include()}", "/[^A-Za-z0-9]/", "-"), "/(-[-]+)/", "-")
remote_state_config_path = run_cmd("${get_repo_root()}/.tools/find-remote-state-config.sh", "${path_relative_to_include()}")
remote_state_config = yamldecode(file(local.remote_state_config_path))
workspace = replace(replace("${path_relative_to_include()}", "/[^A-Za-z0-9]/", "-"), "/(-[-]+)/", "-")
}

// Configure hook to validate the Terraform Cloud workspace is configured for local execution
terraform {
before_hook "validate_tfc_workspace" {
commands = ["import", "plan", "apply", "destroy"]
execute = ["/bin/bash", "${get_terragrunt_dir()}/${path_relative_from_include()}/.tools/verify-tfc-workspace.sh", "${local.remote_state_config.organization}", "${local.workspace}"]
execute = ["/bin/bash", "${get_repo_root()}/.tools/verify-tfc-workspace.sh", "${local.remote_state_config.organization}", "${local.workspace}"]
}
}

Expand Down

0 comments on commit a72ad1c

Please sign in to comment.