janekb04
janekb04

Reputation: 4975

How to share code between github actions in the same repository?

Let's say I want two workflows build.yml and release.yml in my repo. The first one should build the project (let's say using CMake) and the second one should build the project and create a GitHub Release with the built binary.

The project building code is duplicated between the two files. How could it be shared between them, instead of being copy-pasted and having to be manually updated in two places at once?

I have not been able to find a way to achieve any kind of code sharing behavior yet between separate workflows or even jobs within the same workflow.

Upvotes: 11

Views: 5703

Answers (2)

banyan
banyan

Reputation: 4192

Finally, action composition has been released now: https://github.blog/changelog/2021-08-25-github-actions-reduce-duplication-with-action-composition/

Upvotes: 6

Edward Romero
Edward Romero

Reputation: 3104

Option 1: Answer to question above

There is not a current way to do this within github actions directly. There is a couple of steps that you need to go through to make it work.

  1. Build your image
  2. Upload to something like s3 or artifactory after your build is done
  3. Download the image after your previous workflow is done. You can make sure that the workflow is done by triggering second pipeline from the first one
  4. Use the download artifacts

Per github actions

If you need to access artifacts from a previous workflow run, you'll need to store the artifacts somewhere. For example, you could run a script at the end of your workflow to store build artifacts on Amazon S3 or Artifactory, and then use the storage service's API to retrieve those artifacts in a future workflow.

Resources

Option 2: Work around so that we don't have to deal with external services but stay in GitHub

Run two jobs in the same workflow. One job for build and another job for release. The idea here is that you will only run job release when job build is completes successfully. Also we will need to use artifacts to pass data between jobs

Resource

  build:
     ...
     steps:
     - name: Build image
       run: make ...blah blah
     - name: Upload artifact
       uses: actions/upload-artifact@v2
       with:
         name: name-of-build
         path: ./path/to/artifact
  release:
    needs: build # this basically says only run if build job is successful
    steps:
    - name: Download artifact
      uses: actions/download-artifact@v2
      with:
        name: name-of-build
    - name: Release image
      ...

Resource

Upvotes: 4

Related Questions