Assigning environment variables from Spinnaker manifest to an Angular app

74 Views Asked by At

I have Environment-specific variables stored in the spinnaker manifest. I want to replace some variables in the angular app when deployed to dev, qa, and prod environments. How to change my code to achieve this? I am doing this because I do not want to store those variables values in the source code as it is not safe.

I tried to find them my own but failed and I am desperate.

1

There are 1 best solutions below

0
On

A common approach to managing environment variables in many projects is to use .env files. Here is how you can do this for your Angular application:

  1. Creating .env Files:

    • Create a .env file for each environment. For example: .env.dev, .env.qa and .env.prod.
    • Within each file, define your environment variables:
      API_URL=https://api.dev.example.com
      ANOTHER_VARIABLE=value
      
  2. Integrating with Angular:

    • Use a tool like dotenv to load environment variables from the appropriate .env file.
    • During build, you can load the corresponding .env file based on the target environment.
  3. Build Scripts:

    • In your package.json, define build scripts for each environment:
      "scripts": {
        "start:dev": "dotenv -e .env.dev ng serve",
        "start:qa": "dotenv -e .env.qa ng serve",
        "build:prod": "dotenv -e .env.prod ng build --prod"
      }
      
    • This will ensure that the correct environment variables are loaded during development and build.
  4. Accessing Variables in Code:

    • In Angular, you can use environment.ts files to access these variables. For example:
      export const environment = {
        apiUrl: process.env.API_URL
      };
      
    • In your code, you can then import the environment file and access environment.apiUrl.
  5. Security:

    • Remember to add all .env files to your .gitignore to ensure they are not pushed to the repository. This is crucial for keeping secrets and sensitive variables out of version control.

Hope this helps you configure and manage your environment variables effectively for different environments in your Angular application!