简体   繁体   中英

How to parameterize secrets on GitHub Action

We have two branches in repository (dev/prd), each representing a deployment environment. Also we have GitHub action secrets for each branch, in dev branch it should be dev_react_api, in prd branch it should be prd_react_api.

Now we are working on a GitHub action workflow using these secrets secrets.dev_react_api and secrets.prd_react_api

Is there a solution to parameterize GitHub action secrets like the following ?

# only pseudo-code
env:
  branch_name: github.ref

secrets["${env.branch_name}_react_api"]

You can use Environment Secrets for that.

First Goto: Settings -> Environments -> New Environment

Create a new environment and MAKE SURE your environment name matches your branch name

环境秘密

Now you can create any environment secrets that you want, now the trick is, you need two files to use Environment Secrets. First is the main.yml and the second is your (for example) deploy.yml

on:
  push:
    branches:
    - main
    - staging
    - development
    
permissions: write-all

jobs:  
  deploy:
    uses: ./.github/workflows/deploy.yml
    with:
      environment: ${{ github.ref_name }}
    secrets:
      AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }}

The second files that USES the environment:

name: Deployment


on:
  workflow_call:
    inputs:
      environment:
        required: true
        type: string
    secrets:
      AWS_S3_BUCKET:
        required: true


jobs:
  deploy:
    name: Deploy
    environment: ${{ github.ref_name }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@master
      - uses: jakejarvis/s3-sync-action@master
        name: Deploy to S3
        env:
          AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }}
        with:
          args: --acl public-read --follow-symlinks --delete

Now you can create any number of environments with different parameters!

For more details see: https://github.com/olivatooo/github-actions-build-deploy-with-staging-production-environment/

It should work exactly like you have shown with the dynamic name. secrets is just a variable and you provide the key name either explicitly secrets.x implicitly secrets['x'] . Building your key dynamicly works just fine as such. The additional env branch_name is also unneeded since you can just get that value directly in the string.

If you have a paid GitHub plan or are using a public repo, you can also take a look at Environments which take care of this entirely by instead defining two separate environments with the required secrets each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM