How to check if a secret variable is empty in if conditional Github Actions

Viewed 5453

Context

I want to check in my workflow if a secret is present or not before executing a job.

Something like this:

publish:
    runs-on: ubuntu-latest
    if: secrets.AWS_ACCESS_KEY_ID != ''
    steps:
      [ ... ]

However, I've got an error like this when using this expression:

The workflow is not valid. .github/workflows/release.yml (Line: 11, Col: 9): Unrecognized named-value: 'secrets'...

What I tried

I tried to wrote the expression another way:

if: ${{ secrets.AWS_ACCESS_KEY_ID != '' }}
if: ${{ secrets.AWS_ACCESS_KEY_ID }} != ''

Question

How to achieve what I want in a Github Actions workflow?

1 Answers

The Github Action interpreter currently doesn't identify the secrets key word when used in an if conditional expression. Therefore, you can't use the secrets.VARIABLE syntax there.

A workaround found from this issue discussion is to copy the secret to an environment variable first.

Example:

steps:
   env:
     MY_KEY: ${{ secrets.AWS_ACCESS_KEY_ID }}
   if: "${{ env.MY_KEY != '' }}"
   run: echo "This command is executed if AWS_ACCESS_KEY_ID secret IS NOT empty"

If you need to do this at the job level, you would need to create a check-secret job to validate the secrets and then share the result as a output.

Example:

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

  job1:
      runs-on: ubuntu-latest
      needs: [check-secret]
      if: needs.check-secret.outputs.my-key == 'true'
      steps:
        - run: echo "This command is executed if AWS_ACCESS_KEY_ID 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 AWS_ACCESS_KEY_ID secret IS empty"
Related