Checking variable assigned to another variable in rules:if?

Hello,

I have an issue with variables in the rules:if declaration. Here is a piece of my CI code:

.execute on specific branch: &execute_on_specific_branch_rules
rules:
- if: ‘($CI_COMMIT_BRANCH == $GIT_BRANCH) && $TARGET_PATH

deploy to staging:
<<: *set_stage
environment:
name: staging
variables:
GIT_BRANCH: staging
TARGET_PATH: $STAGING_PATH
<<: *execute_on_specific_branch_rules
script:
- *deploy_procedure_scripts

deploy to production:
<<: *set_stage
environment:
name: production
variables:
GIT_BRANCH: master
TARGET_PATH: $PRODUCTION_PATH
<<: *execute_on_specific_branch_rules
script:
- *deploy_procedure_scripts

Please pay attention to $TARGET_PATH. It always returns “true” in the if statement because it’s assigned from another variable ($STAGING_PATH or $PRODUCTION_PATH). I just want to make sure $TARGET_PATH exists and is not empty in order to create a pipeline/job.

If I do this, it works perfectly:

deploy to staging:
<<: *set_stage
environment:
name: staging
variables:
GIT_BRANCH: staging
TARGET_PATH: $STAGING_PATH
rules:
- if: ‘($CI_COMMIT_BRANCH == $GIT_BRANCH) && $STAGING_PATH
script:
- *deploy_procedure_scripts

deploy to production:
<<: *set_stage
environment:
name: production
variables:
GIT_BRANCH: master
TARGET_PATH: $PRODUCTION_PATH
rules:
- if: ‘($CI_COMMIT_BRANCH == $GIT_BRANCH) && $PRODUCTION_PATH
script:
- *deploy_procedure_scripts

How can I make this work without code duplication? This looks like a bug with the revealing of variables.

Hi @georgiharbinger
it is not currently possible. There are several issues related to using variables inside variables like this one or this one. But you can find many more.

1 Like

I’m currently using this:

$TARGET_PATH !~ /^\$/

to check if the variable is populated with something that not begins with a $.

Apparently variable expansion in gitlab ci/cd yaml lack some completeness.

There have been several improvements to variable expansion in newer versions of GitLab since the OP.

Yes, there have been, but I’m currently running v16.2.4-ee and it seems that this specific expansion does not happen yet.
Didn’t check the latest release, but I’am fairly up-to-date.