How do I use secrets in Github Actions?

I have asked this question in stackoverflow and since new users can’t post more than two links, I can’t repost here.

I feel like this is a really stupid question but can’t seem to figure it out. I have set up a really simple node.js project (sohmc/node-secrets-test) with a API_KEY as a secret.

In the node.js.yml action file I have the following:

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
      env:  
        API_KEY: ${{ secrets.API_KEY }} 
    - run: export 
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test

However, in order for export or npm runners to have access to the API keys, the file must be like this:

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - env:                                   <---
        API_KEY: ${{ secrets.API_KEY }}      <---
      run: export                            <---
    - run: env
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test

Why does the documentation say to put the environment variable BEFORE the first run declaration? Is this a bug or a feature? Of the latter, any chance the documentation can be updated?

What exactly are you referring to? The order of keywords within a step shouldn’t matter. A thing that may be important here is that environment variables are not preserved across steps, if that’s what you want you need to set it by writing to ${GITHUB_ENV}. I’d advise against doing that with secrets though, it seems safer to make them available only where absolutely needed.

1 Like

@sohmc,

The environment variables can be set as:

  • workflow-level (env): the global variables can be used by all jobs in the current workflow.
  • job-level (jobs.<job_id>.env): the variables can only be used by the steps in the current job.
  • step-level (jobs.<job_id>.steps.env): the variables can only be used by current step.

When using an action as a step in the workflow, the action may need to use the value of a secret via the environment variable. At this time, you need to map the secret as an environment variable.

  • If the environment variable of the secret is only used by the action, you can map it as a step-level environment variable.
  • If the environment variable of the secret is used by multiple steps in the same job, you can map it as a job-level environment variable.

Of course, you also can directly use the secret in the command lines of the run steps.
For example:

steps:
  - run: curl -H "Authorization: token ${{ secrets.API_AUTH_TOKEN }}" https://api.github.com