Search code examples
c#visual-studio-codeenvironment-variablesvscode-tasks

How do I access .env variables in tasks.json within vscode?


I am trying to use environment variables within task in my tasks.json file of a C# project in vscode.

In my launch.json file I have this code to parse a .env file:

"configurations": [
  {
    ...
    "envFile": "${workspaceFolder}/.env",
  }
]

I then have in the tasks.json file this task:

{
  "label": "login",
  "command": "sh",
  "type": "shell",
  "args": [
    "${workspaceFolder}/etc/login.sh",
    "${env:USERNAME}",
    "${env:PASSWORD}"
  ]
}

This seems to be the code that's implied from https://code.visualstudio.com/docs/editor/tasks, however (from testing by echoing in another task) I have found these last two args to be blank. After researching online I think I have found the reason, the configurations..env is used by the tasks themselves rather than being accessible by task.json that run and so can't be accessed.

How do I create (use) these env variables within the tasks.json?


Solution

  • Checkout https://code.visualstudio.com/docs/editor/tasks-appendix

      /**
       * The environment of the executed program or shell. If omitted
       * the parent process' environment is used.
       */
      env?: { [key: string]: string };
    

    example

    {
        // See https://go.microsoft.com/fwlink/?LinkId=733558
        // for the documentation about the tasks.json format
        "version": "2.0.0",
        "tasks": [
            {
                "label": "diagnostic",
                "type": "shell",
                "options": {
                    "cwd": "${workspaceFolder}/beam",
                    "env": {
                        "FOO": "baz",
                    }
                },
                "command": "printenv",
                "problemMatcher": []
            }
        ]
    }
    

    There is no way I am aware of to pull these from a file like with launch.json

    I would open an issue on the vscode repo