Search code examples
gitlab-ci

String manipulation in .gitlab-ci variables


I'm trying to set up my ci file with some variables. I'm able to generate a variable like so;

...
variables:
    TARGET_PROJECT_DIR: "${CI_PROJECT_NAME}.git"

However, I don't seem to be able to do this;

...
variables:
    PROJECT_PROTOCOL_RELATIVE_URL: "${CI_PROJECT_URL//https:\/\/}.git"

If I run that in bash, I get the expected output which is gitlab.com/my/repo/url.git with the 'https://' removed and the '.git' appended.

My workaround has just been to export it in the 'script' section, but it feels a lot neater to add this to the variables section, since this is part of a template that is being inherited by the actual jobs. Is it possible?


Solution

  • There are several more useful variables defined in the GitLab CI environment.

    CI_PROJECT_PATH gives you the <namespace>/<project name> (or just <project name> if you have no extra namespace) string and CI_SERVER_HOST gives you the server name, so you could do

    variables:
      PROJECT_PROTOCOL_RELATIVE_URL: ${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git
    

    I have similar setups (also without quotes).

    I'm not sure if that will work for you, since my runners and my server are under my control and I don't run pipelines with external projects. But you can get all available variables displayed in the job log by running a job like this:

    stages:
      - env
    
    show-env:
      stage: env
      script:
        - env
    

    Also always helpful is https://docs.gitlab.com/ee/ci/variables/predefined_variables.html