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:
make runmake test- VS Code debugger
- VS Code CodeLens
go rungo 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=""
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")
Testing
Using the same approach, you can make a method in a unit test file like this
func before() {
godotenv.Load("../../.env")
}
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"
}
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": []
}
]
}
Conclusion
That's it. Now, you can debug and test any way you want. Enjoy!
Top comments (0)