如何为多部署配置仅执行一次 Travis CI 'before_deploy' 步骤?

How to execute Travis CI 'before_deploy' step only once for multi-deploy configuration?

在我的项目中,我配置了 Travis CI 构建过程,它将新版本的工件发布到 Git 集线器版本。我的 .travis.yml 文件:

language: java
jdk: oraclejdk8

branches:
  only:
    - master

before_install: mvn package

before_deploy:
  - export TRAVIS_TAG="1.$TRAVIS_BUILD_NUMBER"
  - echo "$TRAVIS_TAG" "$TRAVIS_COMMIT"
  - git config --local user.name "$USER_NAME"
  - git config --local user.email "$USER_EMAIL"
  - git tag "$TRAVIS_TAG" "$TRAVIS_COMMIT"
  
deploy:
  provider: releases
  tag_name: $TRAVIS_TAG
  target_commitish: $TRAVIS_COMMIT
  name: $TRAVIS_TAG
  overwrite: true
  skip_cleanup: true
  api_key: $GITHUB_TOKEN
  file_glob: true
  file:
    - target/my-artifact-$TRAVIS_TAG.jar
  on:
    branch: master

notifications:
  email:
    on_success: never
    on_failure: always

我想添加将工件部署到 Heroku 的功能,为此我在 deploy 步骤中添加了第二项,即:

provider: heroku
api_key: $HEROKU_API_KEY
on:
  branch: master

经过这些更改,Travis 的最终版本 CI 配置:

language: java
jdk: oraclejdk8

branches:
  only:
    - master

before_install: mvn package

before_deploy:
  - export TRAVIS_TAG="1.$TRAVIS_BUILD_NUMBER"
  - echo "$TRAVIS_TAG" "$TRAVIS_COMMIT"
  - git config --local user.name "$USER_NAME"
  - git config --local user.email "$USER_EMAIL"
  - git tag "$TRAVIS_TAG" "$TRAVIS_COMMIT"
  
deploy:
  - provider: releases
    tag_name: $TRAVIS_TAG
    target_commitish: $TRAVIS_COMMIT
    name: $TRAVIS_TAG
    overwrite: true
    skip_cleanup: true
    api_key: $GITHUB_TOKEN
    file_glob: true
    file:
      - target/my-artifact-$TRAVIS_TAG.jar
    on:
      branch: master
  - provider: heroku
    api_key: $HEROKU_API_KEY
    on:
      branch: master

notifications:
  email:
    on_success: never
    on_failure: always

但是使用这种配置的构建失败并显示消息

fatal: tag already exists

The command "git tag "$TRAVIS_TAG" "$TRAVIS_COMMIT"" failed and exited with 128 during

Your build has been stopped.

结果 - 我看到新版本的工件已发布到 Github 版本,但部署到 Heroku 失败。我调查了这个问题,看起来 Travis CI 管道尝试在每个 deploy 之前执行步骤 before_deploy,当它尝试执行它以部署到 Heroku 时,由于 [=39] 而失败=] 已在 before_deploy 步骤中为 deploy 到 Git 集线器版本创建了具有此类名称的标签。

如何解决问题并配置 Travis CI 以仅执行一次 before_deploy 步骤?

我能够在 before_deploy 步骤中使用 if 条件修复发布过程。如果 TRAVIS_TAG 变量已经存在,它将在执行第二次部署之前跳过标记的创建:

before_deploy:
  if ! [[ $TRAVIS_TAG ]]; then
    export TRAVIS_TAG="1.$TRAVIS_BUILD_NUMBER" &&
    git config --local user.name "$USER_NAME" &&
    git config --local user.email "$USER_EMAIL" &&
    git tag "$TRAVIS_TAG" "$TRAVIS_COMMIT";
  fi