diff --git a/src/gitlab-tofu.sh b/src/gitlab-tofu.sh index 1d4eb464f26e68a1a956a64f77aedc3024a8131d..5ffb0a14e3e6d46d37418b870f5d4ee05af55497 100644 --- a/src/gitlab-tofu.sh +++ b/src/gitlab-tofu.sh @@ -244,12 +244,23 @@ if [ $sourced -eq 0 ]; then $TF_IMPLICIT_INIT && terraform_init # shellcheck disable=SC2086 - tofu "${TF_CHDIR_OPT}" "${@}" -input=false -out="${TF_PLAN_CACHE}" ${var_file_args} ${plan_args} + tofu "${TF_CHDIR_OPT}" "${@}" -input=false -out="${TF_PLAN_CACHE}" ${var_file_args} ${plan_args} && ret=$? || ret=$? + + if [ "${OPENTOFU_COMPONENT_PLAN_WITH_JSON}" = 'true' ]; then + if [ "$ret" -eq 0 ] || [ "$ret" -eq 2 ]; then + if ! tofu "${TF_CHDIR_OPT}" show -json "${TF_PLAN_CACHE}" | jq -r "${JQ_PLAN}" > "${TF_PLAN_JSON}"; then + exit $? + fi + + # NOTE: we want to exit with the tofu plan exit code if the tofu show command call is successful. + exit "$ret" + fi + fi + + exit "$ret" ;; "plan-json") - tofu "${TF_CHDIR_OPT}" show -json "${TF_PLAN_CACHE}" | \ - jq -r "${JQ_PLAN}" \ - > "${TF_PLAN_JSON}" + tofu "${TF_CHDIR_OPT}" show -json "${TF_PLAN_CACHE}" | jq -r "${JQ_PLAN}" > "${TF_PLAN_JSON}" ;; "validate") $TF_IMPLICIT_INIT && terraform_init -backend=false diff --git a/templates/plan.yml b/templates/plan.yml index 7f18e99d342ff657aa0a23c402255dcb91be99f3..225ab645cf72e2b96cc3f8334891df7ba539cf4b 100644 --- a/templates/plan.yml +++ b/templates/plan.yml @@ -120,6 +120,11 @@ spec: # NOTE: tofu plan -detailed-exitcode return 2 as exit code # when the plan is non-empty. exit_codes: [2] + artifacts: + # NOTE: we require to always upload artifacts, because when `warning_on_non_empty_plan` is set enabled + # and there is a non-empty plan we have an exit code of `2` which is considered a (failure), + # but we still want to upload all the artifacts. + when: always '$[[ inputs.as ]]': stage: $[[ inputs.stage ]] @@ -152,10 +157,10 @@ spec: TF_ROOT: $[[ inputs.root_dir ]] TF_STATE_NAME: $[[ inputs.state_name ]] TF_PLAN_NAME: $[[ inputs.plan_name ]] + OPENTOFU_COMPONENT_PLAN_WITH_JSON: true OPENTOFU_COMPONENT_VAR_FILE: '$[[ inputs.var_file ]]' image: name: '$[[ inputs.image_registry_base ]]/$[[ inputs.image_name ]]:$[[ inputs.version ]]-opentofu$[[ inputs.opentofu_version ]]-$[[ inputs.base_os ]]$[[ inputs.image_digest ]]' script: - "args=\"\"\nif [ \"$[[ inputs.destroy ]]\" == \"true\" ]; then \n echo \"Planning for a destroy\"\n args=\"-destroy\"\nfi\n" - gitlab-tofu plan $args - - gitlab-tofu plan-json