gitlabgitlab-cipipeline

Gitlab CI pass multiple variable between stage


I want to pass multiple variable between stage

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
    - export var1=$(echo "var1")
    - export var2=$(echo "var2")
    - echo "$var1" >> plan.env
    - echo "$var2" >> plan.env
    - terraform -chdir=terraform plan -out $PLAN
  artifacts:
    paths:
      - terraform/$PLAN
      - plan.env

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

On apply stage, the echo is empty I try to add source $plan.env, on script line on apply stage; but I got another error


Solution

  • The common way that I am aware of for doing this process is to use the dotenv report artifact.

    An example would be something like this:

    stages:
      - first
      - second 
    
    Example First Stage:
      stage: first
      script: 
        - touch job.env
        - echo "VAR1=hi" >> job.env
        - echo "VAR2=${CI_PROJECT_DIR}" >> job.env
      artifacts:
        paths:
          - job.env
        reports:
          dotenv: job.env
    
    Example Second Stage:
      stage: second
      script:
        - echo "$VAR1"
        - echo "$VAR2"