Deploy Laravel .env file based on environment

Viewed 1181

I am creating a CI/CD pipeline for my Laravel application but I kinda don't understand .env environment file. In Laravel docs it is stated that:

To make this a cinch, Laravel utilizes the DotEnv PHP library. In a fresh Laravel installation, the root directory of your application will contain a .env.example file that defines many common environment variables. During the Laravel installation (what is this installation process here?) process, this file will automatically be copied to .env.

Your .env file should not be committed to your application's source control, since each developer/server using your application, could require a different environment configuration

  • Where to store this .env, for different environments if not in the source repo, and make it automatically copied to prod env?

  • Is there any command to create .env file based on provided params that this command can be executed as a part of production deployment and .env file be generated automatically?

  • Do I need to manually copy/paste the production .env file or create some custom Bash script, is there any Laravel/artisan specific way to do this?

  • What does the documentation mean by example env file will be copied during installation process to env, is there any other process different than the initial one?

1 Answers

It's very big decision, depends to your infrastructure and deploy process. Secrets management is not easy. I can show you one way, answered to your questions.

Where to store this .env

  1. Create folder deployment in your project. In this folder create folder environments and subfolders dev, stage, prod, etc
  2. Create .env files with your variables in this folders
  3. Use sops to encrypt this files
  4. Push this files to repo
  5. On deployment process, decrypt file, referring to deploy environment.

Is there any command to create .env

If you have params in array - just make this - variables will be read from env vars

foreach ($params as $key => $value){
    putenv("$key=$value");
}

Do I need to manually copy/paste the production .env

Not, you don't

What does the documentation mean by example env file will be copied during installation process to env

It's mean - example env will be copied at first install, look at composer.json: "post-root-package-install": [ "php -r "file_exists('.env') || copy('.env.example', '.env');"" ],

Related