Search code examples
pythonpytestworkflowgithub-actionstox

Access env variable with tox and Github Action


TL;DR: Empty env variables, but I don't know why.

I have a repo with a local .env file, and a Github Action workflow to launch some workflows when I push my commits to remote. I have also put the secrets of the env file as key-value pairs inside Settings / Environment secrets, one secret env for each line of my env file.

The problem is: when I run my tests locally, everything is fine and my test suite passes without any problem. However, when I push my changes and the workflows start, they (coverage and test) fail because the secret isn't found - and it's mandatory for a test -, even if it should be found.

If it's important, I use tox to run my tests, and also passes the variables in the env block of the tox step. However, when the action is runned, the (snippet of) tox output is:

     def __init__(self):
        token = os.getenv("TELEGRAM_TOKEN", None)
        if not token:
>           raise ValueError("Missing token!")
E           ValueError: Missing token!

My coverage.yml looks like this (tests.yml is similiar regarding the env block):

name: Coverage

on: [push, pull_request]

jobs:
  coverage:
    name: Coverage
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@master
      - name: Setup python
        uses: actions/setup-python@v2
        with:
          python-version: 3.9
      - run: pip install tox
      - run: tox -e coverage
        env:
          TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }}
          TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }}

EDIT: I also found out that tox, by default, limits what's passed as env; however, even with passenv, I have always the same error.

EDIT 2: Snippet of my tox.ini.

[testenv:coverage]
passenv = TELEGRAM_TOKEN TELEGRAM_CHAT_IDS

deps =
    -r requirements/base.txt
    -r requirements/test.txt

commands =
    coverage erase
    coverage run
    coverage html
    coverage xml
    coverage report -m

EDIT 3: After tried with act and with some echo prints, it seems that the environment variables are empty, even if they are set. Somebody can tell me why?


Solution

  • The problem was that the environment was not set for the job (source), so even if the query was correct, the variable was always empty; in fact, when I uploaded the secret to the repository variables, it was detected.

    Adding environment: <name> to the job solved the problem.