diff --git a/tools/terraform.sh b/tools/terraform.sh index ecc08d0..41baf3c 100644 --- a/tools/terraform.sh +++ b/tools/terraform.sh @@ -141,37 +141,43 @@ function tf_plan { export CI_PROJECT_DIR=$(git rev-parse --show-toplevel) fi + set +e # shellcheck disable=SC2086 # shellcheck disable=SC2048 - if ! terraform plan -out "$output.plan" $* | tee "$output"; then - echo "error" - return - fi - - - echo "... transforming into json ..." - terraform show -json "$output.plan" > "$output.json" - - - jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "create") | .address' -r | sort > "$output.create" - # shellcheck disable=SC1083 - if [[ $(wc -l "$output".create | awk {'print $1'} ) -gt 0 ]]; then - printf "\e[92m\e[1mElements to be created .\e[0m\n" - sed -e 's#^#+ #' "$output.create" - fi + terraform plan -detailed-exitcode -out "$output.plan" $* | tee "$output"; + exitCode=$? + set -e + # -detailed-exitcode Return detailed exit codes when the command exits. + # This will change the meaning of exit codes to: + # 0 - Succeeded, diff is empty (no changes) + # 1 - Errored + # 2 - Succeeded, there is a diff + + if [[ $exitCode == 2 ]]; then + echo "... transforming into json ..." + terraform show -json "$output.plan" > "$output.json" + + + jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "create") | .address' -r | sort > "$output.create" + # shellcheck disable=SC1083 + if [[ $(wc -l "$output".create | awk {'print $1'} ) -gt 0 ]]; then + printf "\e[92m\e[1mElements to be created .\e[0m\n" + sed -e 's#^#+ #' "$output.create" + fi - jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "delete") | .address' -r | sort > "$output.delete" - # shellcheck disable=SC1083 - if [[ $(wc -l "$output".delete | awk {'print $1'} ) -gt 0 ]]; then - printf "\e[91m\e[1mElements to be deleted (or recreated).\e[0m\n" - sed -e 's#^#- #' "$output.delete" - fi + jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "delete") | .address' -r | sort > "$output.delete" + # shellcheck disable=SC1083 + if [[ $(wc -l "$output".delete | awk {'print $1'} ) -gt 0 ]]; then + printf "\e[91m\e[1mElements to be deleted (or recreated).\e[0m\n" + sed -e 's#^#- #' "$output.delete" + fi - jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "update") | .address' -r | sort > "$output.update" - # shellcheck disable=SC1083 - if [[ $(wc -l "$output".update | awk {'print $1'} ) -gt 0 ]]; then - printf "\e[93m\e[1mElements to be updated .\e[0m\n" - sed -e 's#^# #' "$output.update" + jq < "$output.json" '.resource_changes[] | select(.change.actions[] == "update") | .address' -r | sort > "$output.update" + # shellcheck disable=SC1083 + if [[ $(wc -l "$output".update | awk {'print $1'} ) -gt 0 ]]; then + printf "\e[93m\e[1mElements to be updated .\e[0m\n" + sed -e 's#^# #' "$output.update" + fi fi }