gitlab-ci

Gitlab-ci.yaml: for loop for release assets


Is it possible to create a for loop or something similar for all of my conf (conf_a, conf_b...) to simplify this .gitlab-ci.yml:

  release:
    tag_name: $CI_COMMIT_TAG
    name: 'Release $CI_COMMIT_TAG'
    description: 'Release created using the release-cli.'
    assets:
      links:
        - name: conf_a
          url: 'https://gitlab.com/-/jobs/${BT_JOB_ID}/artifacts/raw/build/conf_a/conf_a.tar'
        - name: conf_b
          url: 'https://gitlab.com/-/jobs/${BT_JOB_ID}/artifacts/raw/build/conf_b/conf_b.tar'
        - name: conf_c
          url: 'https://gitlab.com/-/jobs/${BT_JOB_ID}/artifacts/raw/build/conf_c/conf_c.tar'
        - name: conf_d
          url: 'https://gitlab.com/-/jobs/${BT_JOB_ID}/artifacts/raw/build/conf_d/conf_d.tar'
        - name: conf_e
          url: 'https://gitlab.com/-/jobs/${BT_JOB_ID}/artifacts/raw/build/conf_e/conf_e.tar'


Solution

  • Unfortunately, there is no builtin way to utilize loops in the yaml definition for release.

    However, the release: keyword is, more or less, just a shorthand way to add script steps to your script: that invokes the release-cli binary.

    With that understanding, it is straightforward to just make a job that uses release-cli directly and will allow you to utilize whatever utility/language you prefer to call release-cli with programmatically generated arguments.

    As a simple, example, you may generate the assets link argument(s) in a loop in bash, then use those arguments to invoke release-cli.

    myjob:
      variables:
        CONF_FILES: "conf_a conf_b conf_c conf_d conf_e"
      script: |
        # generate asset link arguments in a loop
        asset_args=()
        for conf_name in "$CONF_FILES"; do
            url="${CI_PROJECT_URL}/-/jobs/${BT_JOB_ID}/artifacts/raw/build/${conf_name}/${conf_name}.tar"
            asset_info='{"name":"'$conf_name'","url":'$url'"}'
            asset_args+=(--assets-link $asset_info)
        done
    
        # invoke release-cli with those args
        # modify as needed.
        release-cli create \
                     --tag-name $CI_COMMIT_TAG \
                     --description "desc" \
                     "${asset_args[@]}"
    

    This script is untested, but the basic idea should be clear -- and you can use whatever tools or languages you prefer to accomplish the same task of invoking release-cli with programmatically generated arguments.

    Though, it's unclear whether this makes the YAML any cleaner than your original if you only have a small handful of assets. Of course, if you have dozens or hundreds of assets, this can be very useful.

    You could also commit your script to the repo itself, then invoke it like:

    myjob:
      variables:
        CONF_FILES: "conf_a conf_b conf_c conf_d conf_e"
      script:
        - ./create-release.sh