Use two different GitHub environment secrets in single action

Viewed 857

I have created GitHub Environment Secrets for staging and productions for example

Enviroment > Production  > DB_PASS

and

Enviroment > Staging  > DB_PASS

in my workflow I have

on:
 push:
    branches:
      - main
      - staging
jobs:
  deploy:
    environment: Production 
    name: Deploy
    runs-on: ubuntu-latest
    steps:
    - name: Debug Secret 
      run: echo ${{ secrets.DB_PASS}}

How can I change the environment to Staging when branch merged is staging, probably by using gihub.ref for the branch name. I tried passing the value dynamically to environment from the previous job using needs.job1.outputs.output1 but it didn't work.

I found that some developer on Stackoverflow has suggested using a prefix in secret names like

  • PROD_DB_PASS
  • STG_DB_PASS

but is there any better and cleaner way to do this?

1 Answers

Like you mentioned github.ref is probably the best way to go about it.

on:
 push:
    branches:
      - main
      - staging
jobs:
  deploy-production:
    environment: Production 
    name: Deploy production
    runs-on: ubuntu-latest
    if: ${{ github.ref == 'refs/heads/main' }}
    steps:
      - name: Debug Secret 
        run: echo ${{ secrets.DB_PASS }}

  deploy-staging:
    environment: Staging 
    name: Deploy staging
    runs-on: ubuntu-latest
    if: ${{ github.ref == 'refs/heads/staging' }}
    steps:
      - name: Debug Secret 
        run: echo ${{ secrets.DB_PASS }}

Agreed there is a lot of duplicated code, but I think it is simpler, clearer and more reliable than dynamically passing the environment based on some previous job.

Related