SonarCloud Github: always pushed to main branch on "workflow_dispatch"

We are using Github Actions to analyse a dotnet 6 project with the default .yml-file copied from SonarCloud when setting up the project.

The build-command is just dotnet build

When we add workflow_dispatch: to the on:-section, we are able to trigger the action on-demand through the Github-UI

But sonar does not respect the branch from which this manual action run is triggered. The analysis data always gets pushed into the main branch on sonarcloud.

Hi,

I think this is going to be about what was in the env when you triggered analysis. Can you go to the corresponding Background Task and under the cog menu, Show SonarScanner Context and check the ‘Project scanner properties’ section to see if there are any branch or pullrequest parameters defined?

 
Ann

Hi @ganncamp ,

i am very sorry for the late answer, was out of office the last two weeks (and will be the next three :wink: I just checked but unfortunately I cannot access the cog menu because I am no administrator on the project.

We were able to implement a workaround in the github action file to add the sonar-branch-parameter when the build is not in a PR-context like this:

     - name: Build and analyze on PR
        if: ${{contains(github.ref, '/pull/')}}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          ./.sonar/scanner/dotnet-sonarscanner begin /k:"<projectKey>" /o:"<organization>" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io"
          dotnet build
          ./.sonar/scanner/dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}"
          
      - name: Build and analyze
        if: ${{!contains(github.ref, '/pull/')}}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          ./.sonar/scanner/dotnet-sonarscanner begin /k:"<projectKey>" /o:"<organization>" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.branch.name="${{ github.ref_name }}"
          dotnet build
          ./.sonar/scanner/dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}"

It would be nice to hear if there is a better solution or how to configure it correctly. But as we have a workaround for now and I only will be back in September, it’s not urgent at the moment :wink: Have a nice summer :smiley:

1 Like