ScribeMD / docker-cache

Cache Docker Images Whether Built or Pulled
MIT License
98 stars 27 forks source link

Key parameter is evaluated at runtime -- meaning it may change between load & save #823

Open mikaylathompson opened 4 months ago

mikaylathompson commented 4 months ago

I just found and started using docker-cache -- thank you!

We encountered an interesting edge case--I was using hashFiles on the Dockerfiles in our repo for the cache key, but our build script creates a new Dockerfile while it runs. Because the key expression is evaluated at runtime when getInput is called, it was returning a different key at the beginning of execution (loading from the cache) vs the end of execution (saving to the cache). This made it essentially impossible for us to ever have a cache hit.

As a workaround, I added a step to manually hash the files and generate a key beforehand, but I think the "expected" behavior for this tool would be to inherently use the same key for load & save, regardless of whether the conditions used to create the key change.

Code Examples

steps:
  - name: Cache Docker Images
    uses: ScribeMD/docker-cache@0.5.0
    with:
      key: docker-${{ runner.os }}-${{ hashFiles('**/Dockerfile') }}

If the subsequent steps create a new Dockerfile, the Post Cache Docker Images step will generate a new key and save the file to a new cache entry.

The workaround:

steps
    - name: Generate Cache Key from Dockerfiles
      id: generate_cache_key
      run: |
        files=$(find . -type f \( -name 'docker-compose.yml' -o -name 'Dockerfile' \))
        file_contents=$(cat $files)
        key=$(echo "${file_contents}" | sha1sum | awk '{print $1}')
        echo "key=${key}" >> "$GITHUB_OUTPUT"

    - name: Cache Docker Images
      uses: ScribeMD/docker-cache@0.5.0
      with:
        key: docker-${{ runner.os }}-${{ steps.generate_cache_key.outputs.key }}

Here, the key is generated once and used in both the initial and post steps.