Skip to content

Instantly share code, notes, and snippets.

@gberenice
Last active January 28, 2025 14:24
Show Gist options
  • Select an option

  • Save gberenice/4d51f117586cba8359751599b4ed66ac to your computer and use it in GitHub Desktop.

Select an option

Save gberenice/4d51f117586cba8359751599b4ed66ac to your computer and use it in GitHub Desktop.
Steps to Break Up a Terralith - Migration Script
#!/bin/bash
###
### `github_repos_migration.sh` script purpose is to migrate the state to a new GitHub repositories root module.
### This script must be run from your root-modules directory, see below for the expected directory structure.
### └── root-modules
### ├── terralith # legacy root module ($SRC_ROOT_MODULE)
### └── github-repos # new root module ($DESTINATION_ROOT_MODULE)
set -eu -o pipefail
SRC_ROOT_MODULE="terralith"
DESTINATION_ROOT_MODULE="github-repos"
DATE=$(date +"%Y-%m-%d")
DESTINATION_STATE_FILE="github-repos-state-$DATE.tfstate"
SRC_STATE_FILE="terralith-state-$DATE.tfstate"
function mv_resource() {
if ! tofu state mv -state-out="../$DESTINATION_ROOT_MODULE/$DESTINATION_STATE_FILE" "$1" "$1"; then
echo "Check if the resource exists in the source state with: tofu state list | grep $1"
exit 1
fi
}
function main() {
echo "⏳ Starting migration..."
# Change into destination root module so we can pull state file and confirm initialized
cd "$DESTINATION_ROOT_MODULE"
tofu init
# Pull the destination state into a local file so we can move resources to it
tofu state pull > "$DESTINATION_STATE_FILE"
# Confirm the source root module is initialized
cd "../$SRC_ROOT_MODULE"
tofu init
# Pull the source state into a local file as a backup
tofu state pull > "$SRC_STATE_FILE"
# Move resources
mv_resource "github_repository.foo"
mv_resource "github_repository.bar"
# Push the updated state file
cd "../$DESTINATION_ROOT_MODULE"
tofu state push "$DESTINATION_STATE_FILE"
echo "Migration completed 🎉"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment