以某种方式捕获 GitLab 管道错误以供下一个作业使用

Capture GitLab pipeline error somehow for next job to use

# Stage to pull and push image
job1:
  stage: job1


  allow_failure: true

  script:

    # Pull image and save success
    - docker pull ${SOURCE_IMAGEURI}:${TAG}

    ...

    - docker tag ${SOURCE_IMAGEURI}:${TAG} ${TARGET_IMAGEURI}:${TAG} 
    
    # Job might fail here due to not enough permissions which is what I want to happen
    - docker push ${TARGET_IMAGEURI}:${TAG} 

    - echo "Error Message" > curldata.txt
  artifacts:
    when: always
    paths:
      - curldata.txt
job2:
  stage: job2
  script:

    # Do something with the error that happened in job1

  when: always
  dependencies:
    - job1

以上是拉取和推送图像的作业的一部分。有时,由于缺乏权限,作为安全措施,图像将无法推送。我将如何捕获发生的错误,以便我可以将该工件发送到下一个反馈作业。此作业会将信息发送给用户,因此 he/she 知道他们没有足够的权限。

您可以 tee 将命令的 (stderr) 输出到文件并制作文件。

script:
  # ...
  # show output of the command and store stderr to text file
  - docker push ${TARGET_IMAGEURI}:${TAG} 2> >(tee stderr.txt)
artifacts:
  paths:
    - stderr.txt
  when: always

如果您需要在错误后发生一些逻辑,您可以使用 and/or 个逻辑门。

docker push ${TARGET_IMAGEURI}:${TAG} || echo "do this if it fails" > error.txt && exit 1

关于稳健 error handling in bash 还有很多要说的,但这些是您可以使用的一些基本想法。