AI Hints
Home›CI/CD with GitHub Actions Tutorial›Migrations and Delivery Practice
CI/CD with GitHub Actions · Lesson 98 of 138

Practice: Deploy on Tag

Test, then ship.

⏱ 2 min read▶ Video at 1:53:12🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

Practice time. Write a workflow that runs when a version tag is pushed. It should run the tests first, and deploy to production only if they pass. Pause, and try it.

Practice: Deploy on Tag
From the video: Practice: Deploy on Tag
  • Runs on a version tag
  • Test first
  • Then deploy

One answer

The workflow listens for tags starting with v. The test job installs the requirements and runs pytest. The deploy job needs test, uses the production environment, and deploys the version from github dot ref name.

.github/workflows/deploy.ymlyaml
name: Deploy on tag
on:
  push:
    tags: ["v*"]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install -q -r requirements.txt && pytest -q
  deploy:
    needs: test
    runs-on: ubuntu-latest
    environment: production
    steps:
      - run: echo "Deploying ${{ github.ref_name }}"

Running it

Our helper pretends the tag v two point zero point zero was pushed. The tests pass, so the deploy job runs, in the production environment, and deploys v two point zero point zero.

Terminal
run-steps .github/workflows/deploy.yml --tag v2.0.0 | grep -vE "↷|^Workflow|100%"
Job: test
  ✓ Run pip install -q -r requirements.txt && pytest -q
      3 passed in 0.01s
  Job succeeded
Job: deploy
  Environment: production
  ✓ Run echo "Deploying v2.0.0"
      Deploying v2.0.0
  Job succeeded

When tests fail

What if the tests fail? We break the discount function, and push the same kind of tag. The test job fails, so the deploy job is skipped, and nothing broken reaches production. And a tag that doesn't start with v, like release one, doesn't trigger the workflow at all.

Terminal
sed -i 's#percent / 100#percent / 10#' app.py
run-steps .github/workflows/deploy.yml --tag v2.0.1 | grep -E "^Job|✗|skipped"
Job: test
  ✗ Run pip install -q -r requirements.txt && pytest -q
Job: deploy
  - skipped, because a job it needs failed
run-steps .github/workflows/deploy.yml --tag release-1
Workflow: Deploy on tag  (event: push, tag: release-1)
  Not triggered: tag release-1 is not in ['v*']

Summary

Tag triggered deploys, with tests first, are a simple and reliable release flow. Next, practice with staging and production.

Key takeaways
  • tags: ["v*"]
  • needs: test
  • environment: production
Next up: Practice: Staging then Production — two stages