Skip to content

Instantly share code, notes, and snippets.

@brtkwr
Last active December 25, 2025 23:23
Show Gist options
  • Select an option

  • Save brtkwr/0da8cbfd34a040e7a15832dfbd19d698 to your computer and use it in GitHub Desktop.

Select an option

Save brtkwr/0da8cbfd34a040e7a15832dfbd19d698 to your computer and use it in GitHub Desktop.
Usage: ./tf-apply-file.sh example.tf
#!/bin/bash
set -euo pipefail
if [ $# -eq 0 ]; then
echo "Usage: $0 <terraform-file.tf> [additional-terraform-args]"
exit 1
fi
# Check if terraform is available
if ! command -v terraform &> /dev/null; then
echo "Error: terraform command not found"
exit 1
fi
TF_FILE="$1"
shift
if [ ! -f "$TF_FILE" ]; then
echo "Error: File '$TF_FILE' not found"
exit 1
fi
# Extract resource names from the terraform file
RESOURCE_LIST=($(grep -E '^resource\s+"[^"]*"\s+"[^"]*"' "$TF_FILE" | sed -E 's/^resource[[:space:]]+"([^"]+)"[[:space:]]+"([^"]+)".*/\1.\2/'))
if [ ${#RESOURCE_LIST[@]} -eq 0 ]; then
echo "No resources found in $TF_FILE"
exit 1
fi
if [ ${#RESOURCE_LIST[@]} -eq 1 ]; then
# Auto-select single resource
selected_resource="${RESOURCE_LIST[0]}"
echo "Applying target: $selected_resource"
terraform apply -target="$selected_resource" "$@"
else
# Use fzf for selection if available, otherwise fallback to menu
if command -v fzf &> /dev/null; then
# Create options array with "Apply all" option
options=("${RESOURCE_LIST[@]}" "Apply all resources")
selected=$(printf "%s\n" "${options[@]}" | fzf --prompt="Select resource to apply: ")
if [ -z "$selected" ]; then
echo "No selection made"
exit 1
elif [ "$selected" = "Apply all resources" ]; then
# Apply all resources
TARGETS=()
for resource in "${RESOURCE_LIST[@]}"; do
TARGETS+=("-target=$resource")
done
echo "Applying all targets: ${RESOURCE_LIST[*]}"
terraform apply "${TARGETS[@]}" "$@"
else
# Apply selected resource
echo "Applying target: $selected"
terraform apply -target="$selected" "$@"
fi
else
# Fallback to numbered menu
echo "Found ${#RESOURCE_LIST[@]} resources in $TF_FILE:"
for i in "${!RESOURCE_LIST[@]}"; do
echo "$((i + 1)). ${RESOURCE_LIST[i]}"
done
echo "$((${#RESOURCE_LIST[@]} + 1)). Apply all resources"
read -p "Select resource to apply (1-$((${#RESOURCE_LIST[@]} + 1))): " choice
if [[ "$choice" -eq $((${#RESOURCE_LIST[@]} + 1)) ]]; then
# Apply all resources
TARGETS=()
for resource in "${RESOURCE_LIST[@]}"; do
TARGETS+=("-target=$resource")
done
echo "Applying all targets: ${RESOURCE_LIST[*]}"
terraform apply "${TARGETS[@]}" "$@"
elif [[ "$choice" -ge 1 && "$choice" -le ${#RESOURCE_LIST[@]} ]]; then
# Apply selected resource
selected_resource="${RESOURCE_LIST[$((choice - 1))]}"
echo "Applying target: $selected_resource"
terraform apply -target="$selected_resource" "$@"
else
echo "Invalid selection"
exit 1
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment