Search code examples
githubgithub-actions

Dynamically retrieve GitHub Actions secret


I'm trying to dynamically pull back a GitHub secret using GitHub Actions at runtime:

Let's say I have two GitHub Secrets:

  1. SECRET_ORANGES : "This is an orange secret"
  2. SECRET_APPLES : "This is an apple secret"

In my GitHub Action, I have another env variable which will differ between branches

env:
  FRUIT_NAME: APPLES

Essentially I want to find a way to do some sort of variable substitution to get the correct secret. So in one of my child jobs, I want to do something like:

env:
  FRUIT_SECRET: {{ 'SECRET_' + env.FRUIT_NAME }}

I've tried the following approaches with no luck:

secrets['SECRET_$FRUIT_NAME'] }}

I even tried a simpler approach without concatenation just to try and get it working

secrets['$FRUIT_NAME'] }}

and

{{ secrets.$FRUIT_NAME }}

None of the above worked.

Apologies if I have not explained this very well. I tried to keep my example as simple as possible.

Anyone have any idea of how to achieve this?

Alternatively, what I am trying to do is to store secrets on a per-branch basis

For example:

In customer1 code branch: SECRET_CREDENTIAL="abc123"

In customer2 code branch: SECRET_CREDENTIAL="def456"

Then I can access the correct value for SECRET_CREDENTIAL depending on which branch I am in.

Thanks!

Update: I'm getting a bit closer to what I am trying to achieve:

name: Test

env:
  CUSTOMER: CUSTOMER1

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      AWS_ACCESS_KEY_ID: ${{ env.CUSTOMER }}_AWS_ACCESS_KEY_ID
    steps:
    - uses: actions/checkout@v2
    - run: |
        AWS_ACCESS_KEY_ID=${{ secrets[env.AWS_ACCESS_KEY_ID] }}
        echo "AWS_ACCESS_KEY_ID = $AWS_ACCESS_KEY_ID"

Solution

  • I was able to achieve this using the workflow name as the branch specific variable.

    For each branch I create, I simply update this single value at the top of the YML file, then add GitHub Secrets to match the workflow name:

    name: CUSTOMER1
    
    jobs:
      build:
        runs-on: ubuntu-latest
        env:
          AWS_ACCESS_KEY_ID: ${{ github.workflow }}_AWS_ACCESS_KEY_ID
        steps:
        - uses: actions/checkout@v2
        - run: echo "::set-env name=AWS_ACCESS_KEY_ID::${{ secrets[env.AWS_ACCESS_KEY_ID] }}"
        - run: echo $AWS_ACCESS_KEY_ID