Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain a build number that commences at 1 for every branch in Github actions, you can follow these steps:

  1. Set up a workflow file for your repository that includes the following code to generate a unique build ID:
env:
  BUILD_ID: ${{ github.event.repository.name }}-${{ github.sha }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Echo build ID
        run: echo "Build ID: $BUILD_ID"
  1. Add a step to extract the branch name from the Github event and use it to create a new build number sequence for each branch. You can do this by adding the following code to the workflow file:
env:
  BUILD_ID: ${{ github.event.repository.name }}-${{ github.sha }}
  BRANCH_NAME: ${{ github.ref }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Extract branch name
        id: extract_branch_name
        run: |
          echo "Current branch: ${BRANCH_NAME}"
          BRANCH_NAME=$(echo ${BRANCH_NAME#refs/heads/})
          echo "::set-output name=branch_name::$BRANCH_NAME"
        shell: bash

      - name: Set build number
        id: set_build_number
        env:
          BUILD_NUMBER: ${{ steps.extract_branch_name.outputs.branch_name }}-${{ github.run_number }}
        run: |
          echo "::set-env name=BUILD_NUMBER::${BUILD_NUMBER}"
          echo "Build number: ${BUILD_NUMBER}"
  1. Finally, you can use the $BUILD_NUMBER environment variable in your workflow to refer to the unique build number for each branch. For example, you can use it to create artifact names or log messages specific to each branch:
env:
  BUILD_ID: ${{ github.event.repository.name }}-${{ github.sha }}
  BRANCH_NAME: ${{ github.ref }}

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Extract branch name
        id: extract_branch_name
        run: |
          echo "Current branch: ${BRANCH_NAME}"
          BRANCH_NAME=$(echo ${BRANCH_NAME#refs/heads/})
          echo "::set-output name=branch_name::$BRANCH_NAME"
        shell: bash

      - name: Set build number
        id: set_build_number
        env:
          BUILD_NUMBER: ${{ steps.extract_branch_name.outputs.branch_name }}-${{ github.run_number }}
        run: |
          echo "::set-env name=BUILD_NUMBER::${BUILD_NUMBER}"
          echo "Build number: ${BUILD_NUMBER}"

      - name: Build and test
        run: |
          echo "Building branch ${BRANCH_NAME} with build number ${BUILD_NUMBER}"
          # build and test code