Skip to content

Fix post_mr_plan_comment if directory was changed in a before_script step

What does this MR do and why?

Fix post_mr_plan_comment if directory was changed in a before_script step.

In our project we set up some CI-Variables as tfvars in a before_script step. In that step we cd into the ${GITLAB_TOFU_ROOT_DIR} and do not return to the ${CI_PROJECT_DIR} afterwards. gitlab-tofu does handle this situation by cding into the CI_PROJECT_DIR first (see gitlab-tofu.sh#L151), so this hasn't been an issue for us so far.

When we try to use the post_mr_plan_comment option, it fails though:

$ if [ "true" == "true" ]; then # collapsed multi-line command
/bin/sh: eval: line 238: can't open terraform/plan.json: no such file
Uploading artifacts for failed job
Uploading artifacts...
terraform/plan.cache: found 1 matching artifact files and directories 
Uploading artifacts as "archive" to coordinator... 201 Created  correlation_id=01K3FS5NZBY7CEPHHN1F604R9F id=3755075 responseStatus=201 Created token=64_C46FpK
Uploading artifacts...
terraform/plan.json: found 1 matching artifact files and directories 
Uploading artifacts as "terraform" to coordinator... 201 Created  correlation_id=01K3FS5P62SWQJF7EBR3GXZBF3 id=3755075 responseStatus=201 Created token=64_C46FpK
Cleaning up project directory and file based variables
ERROR: Job failed: exit code 1

At first I thought this might be related to the change of the default inputs.root_dir of !281 (merged), but as we set the inputs.root_dir: terraform (as you can see from the paths above) the default had no effect anyway.

While this could be easily fixed on our end by cding back to $CI_PROJECT_DIR in the before_script step, I suggest making the post_mr_plan_comment behave the same way as gitlab-tofu.

How to set up and validate locally

  1. Set up an OpenTofu project in a subdirectory (terraform in this case) with CI/CD using this template and supply these inputs:
include:
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@3.0.1
    inputs:
      root_dir: terraform
      post_mr_plan_comment: true

before_script:
  - cd ${GITLAB_TOFU_ROOT_DIR}
  - echo "my_secret = \"$MY_SECRET\"" > terraform.tfvars
  1. When the plan is executed, it fails because the post_mr_plan_comment part assumes GITLAB_TOFU_ROOT_DIR to be either absolute or relative to the current working dir and therefore resolves the path to
$CI_PROJECT_DIR/terraform/terraform/plan.json
|----- working dir ------|- path in script -|

from here: plan.yml#L263

Edited by Malte Jörgens

Merge request reports

Loading