Github Actions dynamic "if" condition in the reusable workflow - Stack Overflow

admin2025-05-01  1

I'm creating a reusable workflow. I want to implement a dynamic if condition in one of the steps. I want the users to be able to pass a certain input which is evaluated in the if condition, but if the user leaves that input empty, it should be assessed as true and the step runs by default.

eg. This is the step in the reusable workflow:

 - name: Build and Push image
   id: build-image
   uses: docker/build-push-action@v6

It builds the docker image, tags it and pushes it to one or more Docker registries.

Now, the user might want to add an if condition like github.ref == 'refs/heads/main', so that the step runs if the condition is fulfilled.

What I have tried is, to create an input variable if_condition like this:

if_condition:
  description: "Condition to determine if 'Build and Push image' step should execute"
  required: false
  type: string
  default: 'true'  # Default value is true, to ensure the step runs if no condition is provided

and use it in the step like this:

- name: Build and Push image
  if: ${{ inputs.if_condition }}
  id: build-image
  uses: docker/build-push-action@v6

I do realize the type of the input is string and the default is true (which is more like a Boolean), but it is to accommodate user-provided inputs like the one I mentioned above or even other ones like success(), always() etc.

It doesn't work like I expected. I passed the value of the input if_condition as github.ref == 'refs/heads/main' and the step ran, even though the workflow run was on a different branch. I expected the step to be skipped as the result of the if condition would be false, but it didn't skip.

I suspect, GitHub Actions is not evaluating the expression and just treating it as a non-empty string. The function fromJson might help here, but I'm not sure.

Any help would be appreciated. TIA!

转载请注明原文地址:http://www.anycun.com/QandA/1746106946a91766.html