Skip to content

Instantly share code, notes, and snippets.

@carnei-ro
Last active July 8, 2024 15:18
Show Gist options
  • Save carnei-ro/b0e99c33f4e689438e92b478fa3102b6 to your computer and use it in GitHub Desktop.
Save carnei-ro/b0e99c33f4e689438e92b478fa3102b6 to your computer and use it in GitHub Desktop.
dynamically changes lifecycle ignore_changes
#!/bin/bash
# DISCLAIMER: There is a lot of room for improvement in this script. It is a quick and dirty solution.
# Description: This script adds a lifecycle block to a resource or data source in a Terraform file focused on ignore_changes.
# This can be useful in conjunction with terragrunt and its hooks:
#
# terragrunt.hcl content:
#
# terraform {
# source = "git::https://github.com......"
#
# before_hook "lifecycle_ignore_changes_random_password_this_length" {
# commands = ["apply", "plan"]
# execute = [
# "lifecycle_block.sh",
# "${get_repo_root()}/${path_relative_to_include()}",
# "random_password",
# "this",
# "length, override_special",
# # "\\ncreate_before_destroy = true\\n"
# ]
# }
# }
# Variables
PATH_TO_TERRAGRUNT_CACHE="${1}/.terragrunt-cache"
NAME="$2"
IDENTIFIER="$3"
IGNORE_CHANGES="$4"
ADDITIONAL_LIFECYCLE_VALUES="$5"
IS_RESOURCE="${6:-true}"
[[ "$IS_RESOURCE" = "true" ]] && PREFIX="resource" || PREFIX="data"
# Tools
BIN_SED=$(which gsed || which sed)
BIN_AWK=$(which gawk || which awk)
# Function to print usage
print_usage() {
echo "Usage: $0 <path-to-terragrunt-file> <name> <identifier> <ignore_changes> [additional_lifecycle_values] [is_resource]"
echo "Example: $0 . random_password this \"length, min_lower, special\""
}
# Function to check arguments
check_arguments() {
if [ -z "$NAME" ] || [ -z "$IDENTIFIER" ]; then
print_usage
exit 1
fi
}
# Function to find file to modify
find_file() {
local name=$1
local identifier=$2
local prefix=$3
local file
file=$(grep -Rl "${prefix} \"${name}\" \"${identifier}\"" . | grep -E \.tf$)
echo "$file"
}
# Function to add lifecycle block
add_lifecycle_block() {
local file_to_modify=$1
"$BIN_SED" -i -e "/${PREFIX} \"${NAME}\" \"${IDENTIFIER}\"/a \ \ lifecycle \{\n\ \ \ \ ignore_changes = \[ $IGNORE_CHANGES \] \n $ADDITIONAL_LIFECYCLE_VALUES \}" $file_to_modify
}
# Main function
main() {
# Check arguments
check_arguments
# Change directory
OLD_DIR="$(pwd)"
cd "$PATH_TO_TERRAGRUNT_CACHE"
# Find file to modify
file_to_modify=$(find_file "$NAME" "$IDENTIFIER" "$PREFIX")
if [ -z "$file_to_modify" ]; then
echo "Resource not found"
exit 1
fi
echo "Patching lifecycle in $file_to_modify ..."
# Check if lifecycle already exists
if cat $file_to_modify | "$BIN_AWK" "/${PREFIX} \"${NAME}\" \"${IDENTIFIER}\"/,/^}$/" | grep -q "lifecycle {" > /dev/null; then
echo "Lifecycle already exists. Ignoring this script."
exit 0
fi
# Add lifecycle block
add_lifecycle_block $file_to_modify
# Return to original directory
cd "$OLD_DIR"
}
# Call main function
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment