Home > Back-end >  How to pass Github secrets to JSON file
How to pass Github secrets to JSON file

Time:08-03

I wanted to pass secrets from a GitHub action to a JSON file in the same workflow.

# Github secrets
SECRET_TOKEN: 4321

In file.json the SECRET_TOKEN value needs to be fetched.

 # file.json
    {
       secret_token: "SECRET_TOKEN", # should fetch the SECRET_TOKEN from git action
       apiId: "blabla"
    }

Expected Output:

# file.json
        {
           secret_token: "4321",
           apiId: "blabla"
        }

CodePudding user response:

You have several options - you can use pure bash and jq to achieve that or if you are not that experienced, an easier way will be to use one of existing actions from marketplace, like this one:

https://github.com/marketplace/actions/create-json

- name: create-json
  uses: jsdaniell/[email protected]
  with:
     name: "file.json"
     json: '{"app":"blabla", "secret_token":"${{ secrets.SECRET_TOKEN }}"}'

CodePudding user response:

I would suggest you to use the replace-tokens action, as example, suppose this json file:

file.json

{
   secret_token: "#{SECRET_TOKEN}#",
   apiId: "blabla"
}

the action:

- uses: cschleiden/replace-tokens@v1
  with:
    files: 'file.json'
  env:
    SECRET_TOKEN: ${{ secrets.SECRET_TOKEN }}

If you want to use a different token format, you can specify a custom token prefix/suffix. For example, to replace just tokens like `{SECRET_TOKEN} you could add:

- uses: cschleiden/replace-tokens@v1
  with:
    files: 'file.json'
    tokenPrefix: '{'
    tokenSuffix: '}'
  env:
    SECRET_TOKEN: ${{ secrets.SECRET_TOKEN }}
  • Related