How can I check a null variable in a GitLab pipeline when it's declared with a content of another null variable?
Like the variable VAR_NULL below when NO_VAR is null:
variables:
VAR_EMPTY: ""
VAR_NULL: "${NO_VAR}"
Check the pipeline result out where only VAR_EMPTY == "" and NO_VAR == null evaluate to true all others are false.
Pipeline result (a screenshot for convenience, the full result: https://gitlab.com/labaz/test-gitlab-pipeline-null-var/-/pipelines/493036820):

Full pipeline script (https://gitlab.com/labaz/test-gitlab-pipeline-null-var/-/blob/main/.gitlab-ci.yml):
variables:
VAR_EMPTY: ""
VAR_NULL: "${NO_VAR}"
jobTest-Var_Empty-IsNull: # This job runs in the build stage, which runs first.
rules:
- if: '$VAR_EMPTY == null'
script:
- 'echo "VAR_EMPTY IS null"'
jobTest-Var_Empty-IsEmpty: # This job runs in the build stage, which runs first.
rules:
- if: '$VAR_EMPTY == ""'
script:
- 'echo "VAR_EMPTY IS \"\""'
jobTest-Var_Null-IsNull: # This job runs in the build stage, which runs first.
rules:
- if: '$VAR_NULL == null'
script:
- 'echo "VAR_NULL IS null"'
jobTest-Var_Null-IsEmpty: # This job runs in the build stage, which runs first.
rules:
- if: '$VAR_NULL == ""'
script:
- 'echo "VAR_NULL IS Empty"'
jobTest-No_Var-IsNull: # This job runs in the build stage, which runs first.
rules:
- if: '$NO_VAR == null'
script:
- 'echo "NO_VAR IS null"'
jobTest_No_Var-IsEmpty: # This job runs in the build stage, which runs first.
rules:
- if: '$NO_VAR == ""'
script:
- 'echo "NO_VAR IS Empty"'
The problem you're encountering is that VAR_NULL: "${NO_VAR}" is not a null variable. It's actually the same thing as VAR_EMPTY: "" -- you are declaring the variable (therefore it is not null) with an empty value.
The only way to test if the variable was created with another empty variable is to test the original variable itself. That is, test NO_VAR, not VAR_NULL.
An alternative strategy would be to use rules:variables: in order to conditionally declare VAR_NULL
workflow:
rules:
- if: '$NO_VAR' # or '$NO_VAR != null' depending on what you want
variables:
VAR_NULL: "$NO_VAR"
- when: always
jobTest-Var_Null-IsNull:
rules:
- if: '$VAR_NULL == null'
script:
- echo "VAR_NULL is null"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With