wcarhart
wcarhart

Reputation: 2783

How to run tests on PR, deploy on merge with Travis CI

I'm automating the testing and deployment of a web app. I have the following stages that need to run:

  1. Test
  2. Deploy (dev)
  3. Deploy (prod)

When a PR is opened, I'd like only stages 1. (test) and 2. (deploy, dev) to run. Then, when the PR is merged to master, I'd like only stage 3. (deploy, prod) to run. I don't want any CI/CD on regular commits/pushes.

Here's how I'm trying to define my .travis.yml:

# install and other things omitted for brevity
stages:
  - name: dev-test
    if: type = pull_request
    branch:
      except: master
  - name: dev-deploy
    if: type = pull_request
    branch:
      except: master
  - name: prod-deploy
    if: type = pull_request
    branch:
      only: master
jobs:
  include:
    - stage: dev-test
      script: python scripts/dev_test.py
    - stage: dev-deploy
      script: python scripts/dev_deploy.py
    - stage: prod-deploy
      script: python scripts/prod_deploy.py

Right now all three stages run when a PR is opened (not just dev-test and dev-deploy). How should I set up my stages to accomplish what I want?

Upvotes: 1

Views: 864

Answers (1)

wcarhart
wcarhart

Reputation: 2783

I solved this by not using build stages altogether. Instead, I just verify attributes of the GitHub PR in my script directive in .travis.yml, via Travis environment variables.

# install and other things omitted for brevity
script:
  - if [[ $TRAVIS_EVENT_TYPE == "pull_request" ]] ; then python scripts/dev_test.py ; fi
  - if [[ $TRAVIS_EVENT_TYPE == "pull_request" && $TRAVIS_PULL_REQUEST_BRANCH != "master" ]] ; then python scripts/dev_deploy.py ; fi
  - if [[ $TRAVIS_EVENT_TYPE == "push" && $TRAVIS_BRANCH == "master" ]] ; then python scripts/prod_deploy.py ; fi

Upvotes: 4

Related Questions