Search code examples
bashgithub-actions

How to set dynamically outputs variables in a composite action


Issue

I'm trying to set outputs variables dynamically in a composite action action.yml file with bash.

Observation: I don't know what will be the outputs names, they are defined during the action execution using a loop.

In the loop, I'm using the new syntax to set the outputs:

echo "key=value" >> $GITHUB_OUTPUT

However, the outputs variables can't be access in the action following steps in a workflow.

How to reproduce the issue

Relevant part of the implementation I'm using in the action.yml file:

runs:

  using: composite

  steps:

    - run: |

          [...] # Some code to extract and set the KEYS list
 
          for (( i=0; i<${#KEYS[@]}; i++ ))

          do

            RESULT= # Some code to extract KEY value according to KEY name

            echo "'${KEYS[$i]}' value is: $RESULT"
            
            NAME=$(echo "${KEYS[$i]}" | sed 's/[^A-Za-z0-9_]/-/g') # Convert KEY name to correct format without special character

            echo "'${KEYS[$i]}' output name will be: $NAME"

            echo "$NAME=$RESULT" >> $GITHUB_OUTPUT # The problem seems to be here

          done

      shell: bash

Workflow I'm using to test the action:

      - uses: actions/checkout@v3
      
      - name: Call action
        id: read-file
        uses: <owner>/<action-repo>@main # Should set the outputs my-key and my-other-key
      
      - name: Print outputs
        run: |
           echo ${{ steps.read-file.outputs.my-key }}
           echo ${{ steps.read-file.outputs.my-other-key }}

What I tried

Observation: As explained above, all the echo commands print the $NAME and $RESULT values as expected in the action. However, the echo "$NAME=$RESULT" >> $GITHUB_OUTPUT doesn't seem to work as expected, as I'm not able to access the output in the fallowing steps calling the actions.

Question

How can I set those multiple outputs variables dynamically in my composite action using bash?


Solution

  • After some tests, it seems not to be possible to set outputs dynamically in a composite action yet using the echo "key=value" >> $GITHUB_OUTPUT syntax, without configuring the output field name in the action.

    Note: This behavior is supported for Docker and Javascript actions, just not for composite actions.


    At the moment, a workaround for composite actions could eventually be:

    • Set all the key=value in a specific JSON in the action.
    • Save the JSON as a specific output "result".
    • Then, access the values by parsing the "result" JSON in further steps in the workflow.

    It's not as flexible as for a Docker or a Javascript action, but it allows to have the same behavior for all os runners as well.

    PS: I'm open to other workarounds!