Search code examples
bashgitgitlabcontinuous-integrationpipeline

How to use bash script from another repository in gitlab pipeline?


I have two projects in Gitlab. In project A, there are Bash scripts (all located in a single folder). Project B contains a pipeline. How can I implement this? I have already tried using Git submodules, but when I try to initialize and update the submodule in the pipeline, I get an error:

Submodule 'a' (https://gitlab-ss.intranet.x.com/a) registered for path 'b'
Cloning into 'a/b'...
fatal: could not read Username for 'https://gitlab-ss.intranet.x.com': No such device or address
fatal: clone of 'https://gitlab-ss.intranet.x.com/b' into submodule path 'a/b' failed
Failed to clone 'b'.

I replaced the real project name by a, b and x


Solution

  • This is one way to do it:

    1. Clone only the folder (containing the scripts) from project A to use it in the pipelines of project B using the predefined variable CI_JOB_TOKEN. More details about the predefined CI/CD variables can be found here.

       script:
           - |
             git clone --depth 1 --no-checkout https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab-ss.intranet.x.com/namespace/project_name
             cd project_name
             git sparse-checkout set --no-cone scripts_folder
             git checkout
             cd scripts_folder
             ls -a
      
    2. Add execution permission to your scripts (you probably won't need this)

         chmod +x script1.sh script2.sh script3.sh
      
    3. Execute the scripts

       ./script1.sh
       ./script2.sh
       ./script3.sh
      

    All of the above, combined together, should be something like this:

        script:
            - |
              git clone --depth 1 --no-checkout https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab-ss.intranet.x.com/namespace/project_name
              cd project_name
              git sparse-checkout set --no-cone scripts_folder
              git checkout
              cd scripts_folder
              ls -a
              chmod +x script1.sh script2.sh script3.sh
             ./script1.sh
             ./script2.sh
             ./script3.sh