Skip to content

Instantly share code, notes, and snippets.

@TimothyLoyer
Last active April 9, 2020 17:04
Show Gist options
  • Save TimothyLoyer/2075e7abba74ac5b93112897d941a066 to your computer and use it in GitHub Desktop.
Save TimothyLoyer/2075e7abba74ac5b93112897d941a066 to your computer and use it in GitHub Desktop.
A Terraform wrapper that allows use of `-exclude=` arguments to skip slow resources
#!/bin/bash
#description :This script will make a header for a bash script.
#usage :tf plan -exclude=route53 -exclude=s3
#requirements :Install Terraform
get_local_state() {
# List all Terraform resource, data, and module objects in a directory.
# Note: This ignores 'module' objects!
state="$(grep -rho --include="*.tf" -E "^(resource|data).*\"" .)"
# Remove "resource"
state="${state//resource /}"
# Remove quotes
state="${state//\"/}"
# Replace spaces for dot notation
state="${state// /.}"
echo $state
}
ls() {
# Shows combined list of local and remote resource, data, and module objects.
local_state=$(get_local_state)
remote_state=$(terraform state list)
# Merge states
combined_state=("${local_state[@]}" "${remote_state[@]}")
# Deduplicate
combined_state=$(echo "${combined_state[@]}" | sort | uniq)
echo $combined_state
}
exclude() {
# Generates -target arguments for all tf objects minus those specified.
targets=()
for t in $(ls); do
for exc in $@; do
[[ $t == *"$exc"* ]] && continue 2
done
targets+=(-target="$t")
done
echo ${targets[@]}
}
parse_exclude_args() {
# Parses -exclude and turns it into the equivalent list of -target arguments.
excluded=()
for arg in "$@"
do
case $arg in
-exclude=*)
arg="${arg/ /=}"
excluded+=("${arg#*=}")
shift # Remove -exclude= from processing
;;
esac
done
# Flip excluded to -include args for terraform
echo "$(exclude ${excluded[@]}) $@"
}
plan() {
args="$(parse_exclude_args $@)"
echo "Running 'terraform plan' with arguments: $args"
echo
terraform plan $args
}
apply() {
args="$(parse_exclude_args $@)"
echo "Running 'terraform apply' with arguments: $args"
echo
terraform apply $args
}
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment