Search code examples
codemagic

How to pass environment variable in Codemagic scripts section


I'm using Codemagic CI/CD to build a Flutter application. Under the script section, I use separate sections for each functionality. Like this:

scripts: 
    - name: Fetch the build number
        script: | 
            touch major.txt
            touch minor.txt
            touch patch.txt

            major_version=$(curl --header "PRIVATE-TOKEN: ${GITLAB_PERSONAL_ACCESS_TOKEN}" "https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/variables/DEVOPS_IOS_MAJOR_VERSION" | jq -r '.value')
            minor_version=$(curl --header "PRIVATE-TOKEN: ${GITLAB_PERSONAL_ACCESS_TOKEN}" "https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/variables/DEVOPS_IOS_MINOR_VERSION" | jq -r '.value')
            patch_version=$(curl --header "PRIVATE-TOKEN: ${GITLAB_PERSONAL_ACCESS_TOKEN}" "https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/variables/DEVOPS_IOS_PATCH_VERSION" | jq -r '.value')

    - name: Print the build number
        script: |
            echo "New Build version $major_version.$minor_version.$patch_version"

But here, the value that I obtained to major_verison, minor_version, etc are not passed to the next section because I wrote scripts to separate those functionalities. This is the result I'm getting from the section Print the build number:

New Build version ..

I know if I add those commands under one section will work, but is there a way to pass the variables that we create in one section to other?


Solution

  • this is a limitation from shell interpreter side. It's possible to pass environment variable from parent to child process only (for instance if you run another bash script or any command).

    In your case every script section runs a new shell session and you don't have access to environment variables from previous session. To overcome this limitation you can use a file to save and read version values or move all commands to the same script section.