Skip to content

Make CI variables aliasing explicit

Problem

We currently define duplicate variables in order to support legacy names:

    def predefined_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_JOB_MANUAL', value: 'true') if action?
        variables.append(key: 'CI_PIPELINE_TRIGGERED', value: 'true') if trigger_request

        variables.append(key: 'CI_NODE_INDEX', value: self.options[:instance].to_s) if self.options&.include?(:instance)
        variables.append(key: 'CI_NODE_TOTAL', value: ci_node_total_value.to_s)

        # legacy variables
        variables.append(key: 'CI_BUILD_NAME', value: name)
        variables.append(key: 'CI_BUILD_STAGE', value: stage)
        variables.append(key: 'CI_BUILD_TRIGGERED', value: 'true') if trigger_request
        variables.append(key: 'CI_BUILD_MANUAL', value: 'true') if action?
      end
    end

This can have issues where we update one variable and forget to update the relative duplicate/alias, especially if the 2 variables definition are not adjacent in the code. In addition it's sometimes unclear why we have 2 variables for the same thing.

Solution

Introduce an alias: param when appending variables:

    def predefined_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI_JOB_NAME', value: name, alias: 'CI_BUILD_NAME')
        variables.append(key: 'CI_JOB_STAGE', value: stage, alias: 'CI_BUILD_STAGE')
        variables.append(key: 'CI_JOB_MANUAL', value: 'true', alias: 'CI_BUILD_MANUAL') if action?
        variables.append(key: 'CI_PIPELINE_TRIGGERED', value: 'true', alias: 'CI_BUILD_TRIGGERED') if trigger_request

        variables.append(key: 'CI_NODE_INDEX', value: self.options[:instance].to_s) if self.options&.include?(:instance)
        variables.append(key: 'CI_NODE_TOTAL', value: ci_node_total_value.to_s)
      end
    end

The presence of alias would append another variable with the same value to the collection. This helps reducing duplication and make explicit that a variable is an alias of another one.

When a variable is added conditionally it also avoids running the same condition multiple times.

Note: alias: should also support array of strings since in some cases we could have more than 1 alias: #343087 (comment 707931355)

Edited by Fabio Pitino