Using bash case statement in gitlab ci/cd to set variables

57 Views Asked by At

I'm trying to create a pipeline and set some variables from gitlab based of the git branch, in my case staging, master and everything else branch:

---
stages:
  - deploy
  - pre
  - pro

.deployment_env_vars: &deployment_env_vars
  before_script:
    - |
      case "$CI_COMMIT_REF_NAME" in
        staging)
          env='pre'
        ;;
        master)
          env='pro'
        ;;
        *)
          env='dev'
          SSH_HOST=$SSH_HOST_DEV
          SSH_USER=$SSH_USER_DEV
          SSH_PRIVATE_KEY=$SSH_PRIVATE_KEY_DEV
        ;;
      esac
    - project='project'
    - component='api'

variables:

deploy:
  image: python:3.10.10-alpine
  stage: deploy
  when: manual
  except:
    - staging
  <<: *deployment_env_vars
  tags:
    - project-api-dev
  before_script:
    - 'command -v ssh-agent > /dev/null || ( apk add --update openssh )'
    - eval $(ssh-agent -s)
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $SSH_HOST >> ~/.ssh/known_hosts
    - chmod 664 ~/.ssh/known_hosts

But $SSH_PRIVATE_KEY, and $SSH_HOST are empty and the pipeline fails because ssh-add try to add a empty key, if i use $SSH_PRIVATE_KEY_DEV and $SSH_HOST_DEV my pipeline works, seems like gitlab bypass the *) case, anybody know why?

I'm trying to put a \ before *, like this *) but not works:

  case "$CI_COMMIT_REF_NAME" in
    staging)
      env='pre'
    ;;
    master)
      env='pro'
    ;;
    \*)
      env='dev'
      SSH_HOST=$SSH_HOST_DEV
      SSH_USER=$SSH_USER_DEV
      SSH_PRIVATE_KEY=$SSH_PRIVATE_KEY_DEV
1

There are 1 best solutions below

0
flyx On

The merge key docs read:

If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the current mapping, unless the key already exists in it.

Since before_script already exists in the mapping you want to merge into, the before_script from .deployment_env_vars doesn't get merged. << doesn't do recursive merging.

You should use !reference instead.