Conditionally execute github action based on secrets

Viewed 504

I'm looking for a way to check if the owner of the repository has set some variable.

Usecase: I'm a contributor of diyhue, and I want to setup a generic github action to test the app, this should be done for every user, and publish it to docker hub if the owner of the fork has set the secret DOCKER_USERNAME.

That way the github action will only run the publish step if the user configured the required secrets. But the test will always run, resulting in a green checkmark telling changes from the user aren't breaking the code.

2 Answers

I could not find a way to stop the execution of the github actions if secrets where not set. So I build my own action to do just that.

https://github.com/marketplace/actions/secret-input-gate

This action allows the github actions to succeed (or fail) if secrets are not set. Use it to your liking and let me know what you think. Code is completely open-source, so you can make sure I’m not stealing any tokens.

I found an alternative following this issue discussion

As you can't manipulate secrets in an if (conditional) expression (they won't be recognised by the GHA interpreter), a workaround could be to create a job to check if the secret variable is present or not, set the result as an output, an then manipulate it on other jobs as you wish.

Example with DOCKER_USERNAME:

  check-secret:
      runs-on: ubuntu-latest
      outputs:
        my-key: ${{ steps.my-key.outputs.defined }}
      steps:
          - id: my-key
            env:
                MY_KEY: ${{ secrets.DOCKER_USERNAME }}
            if: "${{ env.MY_KEY != '' }}"
            run: echo "::set-output name=defined::true"

  job1:
      runs-on: ubuntu-latest
      needs: [check-secret]
      if: needs.check-secret.outputs.my-key == 'true'
      steps:
        - run: echo "This command is executed if DOCKER_USERNAME secret IS NOT empty"

  job2:
      runs-on: ubuntu-latest
      needs: [check-secret]
      if: needs.check-secret.outputs.my-key != 'true'
      steps:
        - run: echo "This command is executed if DOCKER_USERNAME secret IS empty"
Related