Ci with variable environment

Hello everyone. I don’t know if this is the right way to save code lines or if there is another possibility to run different environments with the same deploy stage.

- deploy

My case. I want to deploy the staging system and the production system in the same way. To do this, I wrote a rule block to define the envioronment in a environment variable which is initialized like this:

  - if: $CI_COMMIT_BRANCH =~ /^release\//
      ENVIRONMENT_NAME: staging
    when: always
  - if: $CI_COMMIT_BRANCH == "main"
      ENVIRONMENT_NAME: production
    when: always
  - when: never

And the deployment stage looks like this:

  stage: deploy
  image: ubuntu:22.04
  - when: manual
  - echo "${ENVIRONMENT_NAME}"
  # ssh config
  - test -z "${SSH_PRIVATE_KEY}" && exit 1
  - test -f "${SSH_PRIVATE_KEY}" && exit 1
  - test -z "${SSH_USER}" && exit 1
  - test -z "${SSH_HOST}" && exit 1
  - test -z "${SSH_PORT}" && exit 1
  - test -z "${SSH_FOLDER}" && exit 1
  - test -z "${SSH_KNOWN_HOSTS}" && exit 1

The rest of the stage is not important for my question which follows now:

When I push to the main branch, everything is working fine and as expected. But if I push in any release branch, the ci variables are missing.

The test to check if the SSH_PRIVATE_KEY is available fails, but the private key variable is available for all stages.

So I’m a bit confused that the variables are available for the main branch (production environment) but not for the release branch (staging environment).

I think it has anything to do with my workflow part but I’m not sure.
I’m not so fimilar with the gitlab ci yaml and maybe it is nonsense to use a variable for the environment name.

Hope anyone can help me.
If I solve this issue on my own, I will share you the solution right here :wink:

Kind regards and thank you very much,


Hey Markus,

Are your release branches protected? If not, is the reason. Your CI variable SSH_PRIVATE_KEY is labeled as protected, which means it will be available only in protected branches (which probably your main branch is, and that’s why it works there).

So, the solution would be either to protect your release branches, or to remove protected checkbox from your CI variables. The rest looks pretty fine.

Hope this helps! :slight_smile:

1 Like


thank you very much
I’ll try it out this evening and give you feedback.


It works!


1 Like

Are your release branches secure? SSH_PRIVATE_KEY is for protected branches like your main one; it might not work elsewhere.