Set an env variable using a CLI tool before launching the debugger in VSCode

537 views Asked by At

I have a Go application which uses a Postgres DB on Cloud (Heroku) and sets the DB Url as an environment variable calling the Heroku CLI as per guidelines.

So the app can be launched with the command

DATABASE_URL=$(heroku config:get DATABASE_URL -a my-db) my-app

Now I would like to launch the app from within VSCode in debug mode but I do not find the right way to set the DATABASE_URL variable before the debug starts. I have tried with preLaunchTask but with no success. The configurations I have used with preLaunchTask are these

launch.json

{
 "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch",
      "mode": "auto",
      "preLaunchTask": "setPostgresDbUrl",
      "program": "${fileDirname}",
      "env": {},
      "args": []
    }
  ]
 }

tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "setPostgresDbUrl",
      "type": "shell",
      "command": "bash ./setUrl.sh"
    }
  ]
}

setUrl.sh

#!/usr/bin/env bash
DATABASE_URL=$(heroku config:get DATABASE_URL -a go-batch)
1

There are 1 answers

0
Picci On

I have been able to solve the problem in a slightly different way, i.e. using an .env file to set an environment variable from which the url is read.

So, in the root folder of the project I have an .env file like this

 the url may change - to get the current url run the command 
# echo $(heroku config:get DATABASE_URL -a go-batch)

DATABASE_URL=postgres://blah-blah-1.eu-west-1.compute.amazonaws.com:5432/blah

Then in the launch.json I specify to read the environment variable values like this

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "LaunchGo",
      "type": "go",
      "request": "launch",
      "mode": "auto",
      //"preLaunchTask": "setPostgresDbUrl",
      "program": "${fileDirname}",
      "envFile": "${workspaceFolder}/.env",
      "args": []
    }
  ]
}