terraformgitlabcontinuous-integration

Gitlab CI Terraform use plan and apply in diferent stage


I want to use terraform plan and terraform apply in different stage, so I use artifacts I build my own docker image with teraform cli.

the structure of my folder

.gitlab-ci.yaml
terraform/main.tf
terrfaorm/variable.tf

$ cat .gitlab-ci.yaml

image: docker_image:0.0

variables:
    PLAN: tfplan
    TF_IN_AUTOMATION: "true"

.terraform-init: &terraform-init
      - terraform -chdir=terraform init -upgrade -backend-config="XX"

stages:
    - validate
    - plan
    - apply

validate:
  stage: validate
  before_script:
    - *terraform-init
  script:
    - terraform -chdir=terraform validate

plan:
  stage: plan
  before_script:
    - *terraform-init
    - terraform -chdir=terraform plan -out $PLAN
  artifacts:
    paths:
      - $PLAN

apply:
  stage: apply
  before_script:
    - *terraform-init
  script:
    - terraform -chdir=terraform  apply -input=false -lock=false -auto-approve $PLAN
  dependencies:
    - plan
  when: manual

I have got this error

Error: Failed to load "tfplan" as a plan file Error: state tfplan: no such ile or directory

I try to looking for with ls command, but I don't find it on stage apply


Solution

  • You correctly determined that the plan file needs to be preserved between stages in the containerized agent, but the parameter values are slightly incorrect due to use of the chdir flag:

    plan:
      stage: plan
      before_script:
        - *terraform-init
        - terraform -chdir=terraform plan -out $PLAN
      artifacts:
        paths:
          - "terraform/${PLAN}"