Problem accessing environment variable

I have read a few threads here and elsewhere on how to do this. This is what I have come up with so far:

  1. Define the environment variable in my shell start-up (zsh on macOS). I can confirm this is working by doing:

# echo $SECRET
too secret
#

  1. Create a build_flag in platformio.ini:

build_flags =
-DENV_SECRET=‘“${sysenv.SECRET}”’

  1. Running pro run --target envdump shows it is in both BUILD_FLAGS and CPPDEFINES:

‘BUILD_FLAGS’: [ ‘-DENV_SECRET='“too secret”'’,

‘CPPDEFINES’: deque([ (‘PLATFORMIO’, 60115),
‘ARDUINO_ESP32C3_DEV’,
(‘ENV_SECRET’, ‘\“too secret\”’),

  1. I then try to use the define in my code:

static const char *SECRET = ENV_SECRET;

  1. However, it resolves to “”.

I have tried accessing the environment variable directly using getenv but this crashes and burns. What else do I need to do to make this work, please?

Could you check this build_flags — PlatformIO latest documentation ?

Hi. Thank you, yes, that was my first attempt. Just to confirm I put:

-DENV_SECRET="${sysenv.SECRET}"

This is what I get:

src/main.cpp:31:63: error: expected primary-expression before ';' token static const char *SECRET = ENV_SECRET;

I get the same error with:

-DENV_SECRET="\\"{sysenv.SECRET}\\""

The version I originally posted gives me the same appearance of quotes in CPPDEFINES as the system-generated ones.

I will try the Advanced Scripting option again, but I didn’t get it working earlier.

Advanced Scripting is proving difficult, too. If I access env[‘ENV’] then env[‘ENV’].keys() contains ‘SECRET’, but if I do env[‘ENV’].get(‘SECRET’) it returns None. And I if I do env[‘ENV’][‘SECRET’] it errors, so it isn’t that the key exists and has value None.

My problem was due to the intervention of my virtual environment. It seems that although the variables were visible at early stages, when it comes to the final stage of deployment to the esp32, it uses a shell that doesn’t respect the virtual environment. I’m not sure how to overcome it, but for now, I can put the variables in .zshrc and it keeps them out of GitHub.

Did you use the single quotes around?

[env:myenv]
build_flags =
    '-D MYSTRING="Text is \\"Quoted\\""'

Hi. Yes, I did, thanks.