How do I get all GitHub secrets into env variables for Actions to access (powershell in my case)?

10.9k Views Asked by At

I read some similar posts but none seem to answer this question. I can set individual GitHub secrets into environment variables in an Action if I know the name of the secret: env: PW_ID0007: "${{secrets.PW_ID0007}}" How can I expose all secrets as environment variables without knowing their names (either in bulk or some way to iterate through them and set them individually?)

3

There are 3 best solutions below

2
On

There is a way to do that. Please check here

- name: view the secrets context
  shell: bash
  run: echo "$SECRETS_CONTEXT"
  env:
    SECRETS_CONTEXT: ${{ toJson(secrets) }}

In that way you will expose all secrets without knowing names:

enter image description here

And know what you need is go through this json using for instance jq and set them as env variable suing following syntax:

 echo "variable_name=variable_value" >> $GITHUB_ENV
0
On

I created an action exactly for that - takes all the secrets and exports them to environment variables.

An example would be:

- run: echo "Value of MY_SECRET1: $MY_SECRET1"
  env:
    MY_SECRET1: ${{ secrets.MY_SECRET1 }}
    MY_SECRET2: ${{ secrets.MY_SECRET2 }}
    MY_SECRET3: ${{ secrets.MY_SECRET3 }}
    MY_SECRET4: ${{ secrets.MY_SECRET4 }}
    MY_SECRET5: ${{ secrets.MY_SECRET5 }}
    MY_SECRET6: ${{ secrets.MY_SECRET6 }}
    ...

You could convert it to:

- uses: oNaiPs/secrets-to-env-action@v1
  with:
    secrets: ${{ toJSON(secrets) }}
- run: echo "Value of MY_SECRET1: $MY_SECRET1"

Link to the action, which contains more documentation about configuration: https://github.com/oNaiPs/secrets-to-env-action

3
On

I came up with a simple solution, which also works for multiline strings. Here is the corresponding GitHub action step:

- name: Expose github environment as shell variables
  env:
    SECRETS_CONTEXT: ${{ toJson(secrets) }}
    VARS_CONTEXT: ${{ toJson(vars) }}
  run: |
    # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-environment-variable
    # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
    EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
    to_envs() { jq -r "to_entries[] | \"\(.key)<<$EOF\n\(.value)\n$EOF\n\""; }
    echo "$VARS_CONTEXT" | to_envs >> $GITHUB_ENV
    echo "$SECRETS_CONTEXT" | to_envs >> $GITHUB_ENV

jq takes every key-value pair of the json and produces an env-command of the following form:

{name}<<{delimiter}
{value}
{delimiter}

For security reasons, the delemiter $EOF is a random string.

Those env-commands are then appended to $GITHUB_ENV, so that they are available in the next steps.