What is the correct way to have a workflow checkout the code for a branch?

I’ve configured two workflows; build and deploy. The deploy workflow depends on “build” and I am using this

on:
  workflow_run:
    workflows: [Build]
    types: [completed]
  workflow_dispatch:

to trigger the deploy workflow. I was surprised to realize that the code that will run for my “deploy” workflow is the action defined in my main branch instead of the branch I’ve pushed the code to. So I push code to branch X, and the build as defined in X will run but then the deploy action as defined in the the main branch will run. That has to be wrong, right? I can solve parts of it by having my checkout steps use ref to use the correct code, but that feels wrong.

Also, if I go to the run for the deploy workflow it will show that it was triggered by the latest commit in main, but when I read the head_sha from the workflow_run event it will actually contain the correct sha, so I can use that to checkout the right branch.

Not sure if this is a bug or me that are missing some concepts.

Looking at the documentation for the workflow_run that’s working exactly as described, GITHUB_REF is the default branch and GITHUB_SHA the latest commit there. Those describe where workflow definitions are looked up.

That’s basically what’s recommended in the Using data from the triggering workflow section, though that example doesn’t use a checkout. :slightly_smiling_face:

One word of caution though: Depending on what might make the build workflow run (a PR, possibly?) the deploy workflow could run on untrusted code.

I see your point around security, which make sense in open source projects but not as much for internal repositories.

So to summarize, the best I can do is to do what I am doing I guess, that is, look at the head_sha in the event and use that when checking out the code. I just need to remember that when I want to change the workflow it needs to be committed to main for the changes to take effect.

1 Like

If you are dealing w/ internal repositories and want to test something w/o breaking everyone else, you can use a copy of the repository and either change the default branch or push to it.

You will definitely want to test workflow changes before they go live. Personally, I do this by using a copy of my repository. (Usually this is a linked fork, but sometimes I use disconnected clones instead of linked forks.)