Add new environment variables to .env when installing a package

3.6k views Asked by At

In our company, several internal projects rely on the same copied code parts to handle connections to the same APIs (like: Google Suite, JIRA,...). To avoid copying the same code over and over again for new projects, I want to create Symfony packages that collect these API classes.

The tricky part: I'm looking for a way to add the neccessary env variables automatically to .env, just like Symfony's recipe structure does it. But as these projects should only be used internally, pushing their recipe configuration to a public repository is a no-go for me. Adding a custom recipe server (like the one by moay) looks interesting to me, but needs additional configuration in each projects composer.json.

Is there any better way to resolve this, such that I could simply define the needed variables solely in my project, such that they get added to .env without any additional magic?

NB: anything that requires symfony/flex is fine, as this should be part of all new projects in our company

These are solutions I want to avoid:

  • add configuration to bundles / packages itself, such that these configuration values are put under version control
  • add configuration through any other command that is run manually after installing
2

There are 2 answers

1
Nicoweb On

In Symfony, the .env file is now committed into the repository. So It's not a good practice to put sensitive data on it.

A better solution is to create a file name .env.local. This file is not committed and it overrides all environnement value in .env

so you could have in .env

MY_SENSITIVE_DATA=mypersonalkey

and in your .env.local

MY_SENSITIVE_DATA=the_real_sensitive_data

source: https://symfony.com/doc/current/configuration.html#overriding-environment-values-via-env-local

8
Cesur APAYDIN On

You can use composer events for this process. After the package is installed, you add it to the .env file with a symfony command.

https://getcomposer.org/doc/articles/scripts.md

Composer unable to run post install script

There is a sample in the symfony composer.json file.

...
"scripts": {
    "auto-scripts": {
        "cache:clear": "symfony-cmd",
        "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
        "@auto-scripts"
    ],
    "post-update-cmd": [
        "@auto-scripts"
    ]
},
...

After each update or installation, this command is run "post-update-cmd, post-install-cmd".