79338973

Date: 2025-01-08 11:38:13
Score: 1
Natty:
Report link

GitHub reusable workflows inputs and secrets are defined and passed separately and this is why we can't pass secrets as a build arguments values.

However, can workaround this in the following way

  1. Define a secret ARG_ONE.
  2. Pass a secret build argument with a value of a variable name, same as defined secret name
    build_args: |
      ARG_ONE=${ARG_ONE}
      ARG_TWO=ARG_TWO_plain_text
    
  3. Add a step to reusable workflow to substitute variable ${ARG_ONE} wit the value of secret ARG_ONE.
  4. Redefine build_args variable with the substituted value and pass it as a multiline.
  5. Pass build_args as usual to docker/build-push-action action.

Substituted variable value in build_args will be masked as a regular secret.

docker.yml
name: Docker

on:
  workflow_dispatch:

jobs:
  build-and-push:
    name: Build and Push
    uses: org/repo/.github/workflows/docker-reusable.yml@main
    with:
      docker_file: docker/Dockerfile
      build_args: |
        ARG_ONE=${ARG_ONE}
        ARG_TWO=ARG_TWO_plain_text
    secrets: inherit
docker-reusable.yml
name: Docker reusable workflow

on:
  workflow_call:
    inputs:
      docker_file:
        default: Dockerfile
        description: Dockerfile
        required: false
        type: string
      build_args:
        default: ''
        description: Build arguments
        required: false
        type: string

env:
  DOCKER_FILE: ${{ inputs.docker_file }}
  BUILD_ARGS: ${{ inputs.build_args }}

jobs:
  build:
    name: Build and push
    runs-on: ubuntu-latest
    steps:
      - name: Secrets to variables
        if: ${{ env.BUILD_ARGS != '' }}
        uses: oNaiPs/[email protected]
        with:
          secrets: ${{ toJSON(secrets) }}
          exclude: DOCKERHUB*

      - name: Substitute build args
        if: ${{ env.BUILD_ARGS != '' }}
        run: |
          {
            echo 'BUILD_ARGS<<EOF'
            echo "${{ env.BUILD_ARGS }}"
            echo EOF
          } >> "$GITHUB_ENV"

      - name: Build and Push by digest
        id: build
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ${{ env.DOCKER_FILE }}
          platforms: linux/amd64,linux/arm64
          push: true
          build-args: |
            ${{ env.BUILD_ARGS }}
          labels: ${{ steps.meta.outputs.labels }}

This partial example is based on Build and load multi-platform images from Examples.

We added two optional steps, which will be executed only when build_args input is passed and we use oNaiPs/secrets-to-env-action to expose secrets as variables.

Security considerations
Credits
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: Slava