I have a project with terraform code , to create resource in aws. my gitlab ci file (sample below ) has few jobs . I would like to run before_script section before each job , i.e. validate ,apply. how can i achieve this?
stages:
- validate
- plan
- apply
image:
name: terraform_image_path
before_script:
- export AWS_ACCESS_KEY=${AWS_ACCESS_KEY_ID}
- export AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
- rm -rf .terraform
- terraform --version
- terraform init
validate:
stage: validate
script:
- terraform validate
plan:
stage: plan
script:
- terraform plan -out $Terraform_Plan
dependencies:
- validate
artifacts:
paths:
- $Terraform_Plan
apply:
stage: apply
script:
- terraform apply -input=false $Terraform_Plan
dependencies:
- plan
when: manual
....
...
As per the official documenation1:
Use before_script to define an array of commands that should run before each job’s script commands, but after artifacts are restored.
This is as it suggests in the docs. Your before_script
will run before any of the defined jobs.
Here's a minimum working example:
before_script:
- echo "This is executed before each job"
job1:
script:
- echo "This is Job 1"
job2:
script:
- echo "This is Job 2"
And the result:
For your reference, here's the repository: