How do I use secrets in Github Actions?

Viewed 1964

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 with a API_KEY as a secret.

In the nodejs action yml 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

API_KEY doesn't show in export as I would expect it to nor does it show when I console.log(process.env).

According to the documentation, this should work as-is. I feel like I'm missing something really simple.

This is not a fork as suggested in this stackoverflow question.

What am I missing to get the API_KEY available in my node script?

1 Answers

Environment variables can be defined on three levels:

The preference is given to the most specific variable available. For example:

env:
  VAR: I am global
jobs:
  job1:
    steps:
      - run: echo "$VAR"  # "I am global"
  job2:
    env:
      VAR: I am on the job level
    steps:
      - run: echo "$VAR"  # "I am on the job level"
      - env:
          VAR: I am on the step level
        run: echo "$VAR"  # "I am on the step level"
      - run: echo "$VAR"  # "I am on the job level"

To set an environment variable in a step, dynamically, and make it available for further steps, you have to use an environment file (this has changed recently from using workflow commands, which are now deprecated for environment variables):

steps:
  - name: Set the variable
    run: echo "foo=bar" >> "$GITHUB_ENV"
  - name: Print the variable
    run: echo "$foo"  # bar

The old, now deprecated way would set it like this:

run: echo "::set-env name=foo::bar"

but this now triggers a deprecation warning.

Related