DEV Community

Cover image for Debug and Test Operator SDK in VS Code
Chris Lenard
Chris Lenard

Posted on

Debug and Test Operator SDK in VS Code

If you built a kubernetes operator with Operator-SDK and you need to use environment variables, you will find it difficult to debug and test in VS Code. There are many avenues to debug and test:

  1. make run
  2. make test
  3. VS Code debugger vscode debugger icon
  4. VS Code CodeLens vscode CodeLens UI
  5. go run
  6. go test

.env File

First, we need to centralize all environment variables into a .env file in the project root.

Here is an example of how the .env file should look.

FOO_BAR=barfoo
DEBUG_LEVEL=info
WATCH_NAMESPACE=""
Enter fullscreen mode Exit fullscreen mode

The only caveat is your file must NOT contain any # characters. Makefile uses # for comments and will not play friendly.

godotenv Package

Next, you will add the godotenv package, which reads .env and creates environment variables.

Now, in main.go add to the beginning of the main function

// Set env vars, if available.
godotenv.Load("./.env")
Enter fullscreen mode Exit fullscreen mode

Testing

Using the same approach, you can make a method in a unit test file like this

func before() {
  godotenv.Load("../../.env")
}
Enter fullscreen mode Exit fullscreen mode

Call before() at the beginning of any test that requires environment variables.

VS Code

These changes are necessary to make VS Code CodeLens work. Add this property to .vscode/settings.json

{
  "go.testEnvFile": "${workspaceFolder}/.env"
}
Enter fullscreen mode Exit fullscreen mode

and the envFile property to .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "FooBar",
      "type": "go",
      "request": "launch",
      "mode": "auto",
      "program": "${workspaceFolder}/main.go",
      "envFile": "${workspaceFolder}/.env",
      "args": []
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it. Now, you can debug and test any way you want. Enjoy!

Top comments (0)