Commit c6d84511 authored by Alexis Deruelle's avatar Alexis Deruelle
Browse files

fix: tf-validate: remove cached terraform.tfstate

In 'tf-validate' job, terraform validate will try to access the remote
backend when it's already configured, which happens because .terraform/
folder is cached (backend config is stored in
.terraform/terraform.tfstate).

However with the GCP variant currently the pipeline has no credentials
in place yet at this stage and the '-backend=false' flag is not enough
to prevent this from happening in this case.

The problem is well documented, see
https://github.com/hashicorp/terraform/issues/33726#issuecomment-1697854309

Solution:

 - hide the pre-configured backend setup by removing the
   terraform.tfstate file beforehand in the tf-validate script
 - setting the cache policy to pull in order to keep the file for subsequent
   jobs

Fixex: #80
parent 09f54e00
Loading
Loading
Loading
Loading
+10 −0
Original line number Diff line number Diff line
@@ -1156,6 +1156,14 @@ tf-validate:
  stage: test
  needs: []
  script:
    - |-
      # Cached backend configuration in `.terraform/terraform.tfstate` may lead to
      # authentication failure of the `terraform init` command even with `-backend=false` flag
      # see https://github.com/hashicorp/terraform/issues/33726#issuecomment-1697854309
      if [[ -f $TF_PROJECT_DIR/.terraform/terraform.tfstate ]]; then
        log_info "--- \\e[32mpre-init\\e[0m tf-validate: removing cached .terraform/terraform.tfstate to disable any preconfigured backend"
        rm "$TF_PROJECT_DIR/.terraform/terraform.tfstate"
      fi
    - tf_pre_init
    - terraform init -backend=false
    - terraform validate
@@ -1164,6 +1172,8 @@ tf-validate:
    - if: '$TF_VALIDATE_ENABLED != "true"'
      when: never
    - !reference [.test-policy, rules]
  cache:
    policy: pull

tf-docs:
  extends: .tf-base