petercinibulk / envied

Handles environment variables in dart from a .env file.
MIT License
147 stars 34 forks source link

[Question] Best practice for CI/CD? #115

Closed callmephil closed 6 days ago

callmephil commented 1 week ago

I'm trying to use envied with CI/CD (Bitbucket Pipeline & Codemagic) and I'm unsure how to handle the file generation process.

It says in the doc that:

IMPORTANT! Add both .env and env.g.dart files to your .gitignore file, otherwise, you might expose your environment variables.

So if I can't publish the env.g.dart it mean that I need to generate it using a pre-build? This will also be true for the .env file right? Is it the recommended approach?

techouse commented 6 days ago

Here's how I usually handle this:

  1. add all your secrets and/or variables to Github Secrets

  2. inside your env/ directory create an .env.example file containing just the keys without any values, i.e.

    SOME_API_KEY=
  3. inside a Github Action, copy these secrets / variables to your.env files, i.e.

    - name: Create environment files
    env:
    SOME_API_KEY: ${{ secrets.SOME_API_KEY }}
    working-directory: env
    run: |
    set -e
    cp .env.example .env
    sed -i "s#SOME_API_KEY=.*#SOME_API_KEY=$SOME_API_KEY#" .env

    The example above uses sed to find & replace values in your .env file as it is the most readily available *nix tool that does the job.

  4. in your Github actions run the code generation to generate env.g.dart (or any other *.g.dart file) using

    - name: Run the build system for Dart code generation and modular compilation
    run: |
    flutter pub run build_runner clean
    flutter pub run build_runner build --delete-conflicting-outputs
  5. once all the files have been generated THEN build your app

  6. upload your app to the app stores

  7. delete all/any generated files / token files / builds etc in order not to expose any secrets using, i.e.

    - name: Clean up
    if: ${{ always() }}
    run: |
    rm -rf env/.env*
    if command -v flutter &>/dev/null; then
      flutter pub run build_runner clean
      flutter clean
    fi
    rm -rf build
    rm -rf debug_info

I hope this helps.