Search code examples
iosfastlane

Fastlane: How to load .env file from parent directory according to --env


  1. I know that Fastlane automatically load variables from .env, .env.default and .env.{environment}, where environment is supplied by the flag --env in the fastlane command.
  2. In my Fastfile, I need fastlane to load my environment files, that are located in the parent directory.
  3. I want to keep the behavior of loading of loading the .env.{environment} file, when {environment} changes according to what I pass in the --env flag.

Solution

  • This one worked for me:

    1. Using the following before_all inside my platform block:
      before_all do |lane|
        Dotenv.overload '../../.env'
        environment = lane_context[SharedValues::ENVIRONMENT]
        unless environment.nil?
            puts "Load .env file of #{environment}"
            Dotenv.overload '../../.env.' + environment
        end
      end
    
    1. (Important!) Putting a blank .env file in the fastlane directory.

    The reason to create an empty .env is documented in my empty .env file:

    TL;DR: do NOT delete this empty file

    This file is blank to make Fastlane define the SharedValue::ENVIRONMENT variable, which is part of our fastlane/Fastfile configurations.

    As you can see in Fastlane's cli_tools, Fastlane removes the --env index from ARGV pretty early so we can't know what the user passed to the --env parameter.

    Unfortunatly, Fastlane search the .env files only in the fastlane folder and in it's parent folder (the ios folder, in our case). It means that, in our project, Fastlane won't find any .env files. (Source)

    When Fastlane fails to find .env files, it does not call the function load_dot_envs_from, which is responsible to define the SharedValue::ENVIRONMENT variable, which we use inside our Fastfile (Source)

    This file is a hack that will make Fastlane find an empty .env file. It will then set the SharedValue::ENVIRONMENT to the ARGV value. We then use SharedValue::ENVIRONMENT inside Fastlane to load the right file from the right place.