JScott
JScott

Reputation: 148

Use RegEx comparison in Gitlab workflow rules

I'm trying to use a regex comparisons in the workflow:rules section of my gitlab-ci file, but it doesn't seem to be working. Here is a basic version:

stages:
  - prep

variables:
  VAR1: "no value"
  APPURL: "no value"

workflow:  #Goal: only run pipeline for push events set some variables based on branch/commit_ref_name
  rules:
    - if: "CI_PIPELINE_SOURCE == "push"
    - if: "CI_COMMIT_REF_NAME =~ /^dev/
      variables:
        VAR1: "Dev Value"
        APPURL: "https://devurl.com"

test_job:
  stage: prep
  image: runner.image/url
  script:
    - echo "$VAR1"
    - echo "APPURL"

When push a change from a branch named something like "dev1-jirastory", the test job output says "no value" for both variables. So, its not catching the commit_ref_name rule for some reason.

Can someone tell me if you can use regex comparisons in the workflow:rules statements? All the stuff I've found so far refers to job rules. As I want these variables set for multiple jobs, I want to set them for the entire workflow and subsequent jobs, not use the same rules in every single job, which can grow and not be managable.

I did try accomplishing those value determinations in a root "before_script" section, but that gets overwritten if I need to have to do other actions in a before_script for any individual job, so that won't work for me either.

Lastly, if anyone can tell me if I can do any "command" statements for parsing the commit_ref_name, that would be great. I'd love to do something like:

"$CI_COMMIT_REF_NAME" | awk -F "-" '{print $1}')

to pull out the "dev1" portion of the ref name like my sample above for use in jobs as well.

Thanks in advance.

Upvotes: 0

Views: 3056

Answers (1)

danielnelz
danielnelz

Reputation: 5136

Using variables in workflow works, just a couple of small changes needed for your pipeline:

stages:
  - prep

variables:
  VAR1: "no value"
  APPURL: "no value"

workflow:  #Goal: only run pipeline for push events set some variables based on branch/commit_ref_name
  rules:
    - if: '$CI_PIPELINE_SOURCE == "push"'
    - if: '$CI_COMMIT_REF_SLUG =~ /^dev/'
      variables:
        VAR1: "Dev Value"
        APPURL: "https://devurl.com"

test_job:
  stage: prep
  script:
    - echo "$VAR1"
    - echo "$APPURL"

You where missing the $ before the variables in you rules clauses. And I would recommend to use $CI_COMMIT_REF_SLUG instead of CI_COMMIT_REF_NAME to be independent of the case.

Upvotes: 1

Related Questions