Search code examples
codemagic

Conditionaly use Environment Variables depending on Branch Name


I have two different environments.

  • dev
  • prod

In the codemagic.yaml I want to use the same environment variable key, e.g., $FIREBASE_PROJECT_ID. Depending on the branch triggering the build, I want the respective variable value.

According to the official documentation I can use the variable groups. This means that for the same variable name I can set a different value as long as the variables belong to different groups.

From the built-in environment variables, I can utilize the CM_BRANCH to check which branch triggered the pipeline.

How can I set to choose which environment variable value should be used according to the branch? I couldn't find anything around this.


Solution

  • here is some ideas how you can handle such configuration

    Option 1 (works better with simple pipelines)

    • you define 2 environment variables $PROD_FIREBASE_PROJECT_ID and $DEV_FIREBASE_PROJECT_ID
    • in codemagic.yaml you can use something like this
    if [ "$CM_BRANCH" == "main" ]; then 
      export FIREBASE_PROJECT_ID=$PROD_FIREBASE_PROJECT_ID
    else  
      export FIREBASE_PROJECT_ID=$DEV_FIREBASE_PROJECT_ID
    fi
    
    # replace with your command
    gcloud --quiet config set project $FIREBASE_PROJECT_ID
    
    ...
    

    Option 2 (for bigger projects)

    • create prod and dev environment groups with $FIREBASE_PROJECT_ID variable name
    • in codemagic.yaml you can use YAML aliases to define your commands
    definitions:
      scripts:
        - &my_script
          name: Use $FIREBASE_PROJECT_ID
          scripts: gcloud --quiet config set project $FIREBASE_PROJECT_ID
    
    ...
    
    • now you can add workflows for each branch/environment. For instance:
    workflows:
      prod:
        triggering:
          events:
            - pull_request
            - push
          branch_patterns:
            - pattern: main
        scripts:
          - *my_script
        environment:
          group:
            - prod
    
    • for dev workflow you need to use dev group and also you can add/modify script steps if needed

    I hope it helps.