Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to access a Symfony secret value in userland code?

Tags:

php

symfony

Despite making them appear to be environment variables, Symfony does not actually load secrets into the environment, so you can't access them via getenv() or $_ENV. Is there any way to access them other than via DI? I'm trying to have the secret name be stored as an entity property in a database, then have a service class read the appropriate secret's value for whichever entity is requested by the API client.

like image 903
Justin McAleer Avatar asked Sep 20 '25 21:09

Justin McAleer


2 Answers

You can add your env values to your parameters in config/services.yaml like that (you can even have them be booleans, JSON or whatever) :

parameters:
    your_secret: '%env(YOUR_SECRET)%'
    your_bool: '%env(bool:YOUR_BOOL)%'
    your_json: '%env(json:YOUR_JSON)%'

Then you can, for example, retrieve it from a controller like so:

    $yourSecret = $this->getParameter('your_secret');
like image 200
Saphir Avatar answered Sep 22 '25 12:09

Saphir


In production, secrets:decrypt-to-local is recommended for performance reasons. This creates .env.prod.local and the secrets are then available in $_ENV.

When deploying, I use:

php bin/console secrets:decrypt-to-local --force --env=prod

Locally, instead of using dev secrets, I keep the values in .env.local

like image 29
Rhydian Roberts Avatar answered Sep 22 '25 13:09

Rhydian Roberts