简体   繁体   中英

How can I use Github secrets in JS files

I have a basic git repo set up with github actions to build and deploy (HTML and TS files mainly).

However I have to use in some API Keys that needs to be secret.

So I figure out to use GITHUB SECRETS for them.

How can I access GITHUB SECRETS in my js (or TS) files so it can build with github actions properly?

You can pass-in Secrets as ENV variables.

Example:

   ...
   steps:
      - name: Git checkout
        uses: actions/checkout@v2

      - name: Use Node 12.x
        uses: actions/setup-node@v1
        with:
          node-version: 12.x

      - name: Install Dependencies (prod)
        run: yarn install --frozen-lockfile --production

      - name: Run Tests (JEST)
        run: yarn test --ci --silent --testPathIgnorePatterns=experimental
        env:
          CI: true
          API_KEY: ${{ secrets.API_KEY }}

In Node.js you can access it via process.env.API_KEY .

I Find a way to achieve it although it might not be the best (And I'm definitly not bash expert)

So create a setEnv.sh file

mkdir env
echo "export const environment = { firebase_api_key : '$1' }"  > env/env.ts

That take as your API key as first parameter, create a env folder and save TS code with your api key.

Then add this line

- run: sh setEnvironment.sh ${{ secrets.FIREBASE_API_KEY }}

Into your github action script, which will execute your script and set the Secret Key.

You'll now just have to use environment.firebase_api_key in your code.


Your build needs to encrypt your key otherwise it will be exposed.您的构建需要加密您的密钥,否则它将被暴露。 But this can be usefull for example if you use API keys on your website and you also want your website code to be available in public on Github, without those plain keys.

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

An example would be:

...
- run: node -e "console.log(process.env.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: node -e "console.log(process.env.MY_SECRET1)"

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

You should be able to use them after running the action in your JS code using process.env.MY_SECRET1

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