Variable as a result of if statement


I’m new to scripting. I just want to use a variable.
Here is an example. The variable RG is assigned “if”, obviously not what I’m after.

      working_directory: /temp
        - image: azuresdk/azure-cli-python:2.0.22
        - RG: if [[$CIRCLE_BRANCH=="preproduction"] then Preproduction else Production fi
        - attach_workspace:
            at: .
        - run: az login -u $AZURE_LOGIN -p $AZURE_PASSWORD
        - run: az account set --subscription MySubscription
        - run: az group deployment create --resource-group $RG --mode Incremental --template-file Facture.ResourceGroup.json --parameters @Facture.Parameters.$RG.json
        - run: az webapp deployment source config-zip -g $RG -n facturesWebApi$RG --src
        - run: az webapp deployment source config-zip -g $RG -n facturesAngular$RG --src


I’d remove that environment key completely and try setting the env var in an early run command. You can find out how to do bash conditionals by searching the web (e.g. “bash string equality comparison”).

Once the var is set you may have to export it, which you can do in the same command.


I’ll try. However, it seems I can only export a variable for a job. what if I want a variable available accross jobs?


If I do the following, then RG is echoed correctly:

- run: 
          command: |
            export RG=if [$CIRCLE_BRANCH=="preproduction"] then "Preproducion" else "Production" fi
            echo $RG

However if I do

- run: if [ $CIRCLE_BRANCH == "preproduction" ]; then export RG="Preproduction"; else export RG="Production"; fi
      - run: echo $RG

then echo display an empty string.

Hence, how can I export outside of the scope of the run?


I just swicthed from running multiple “run” in my jobs to running one run with multi-lign command so I can use the exported variable.
However, I haven’t found a solution to use an exported variable accross jobs.


To be clear, are your two run commands in the same steps section? The different indentation levels seem to indicate they are not.

I’m afraid I don’t know the answer either way, but it would be worth clarifying, in case someone else can advise you.


You can do this by exporting the result to a file with something like

if ... then 
  echo 'export RG =val' >>
echo "source" >> $BASH_ENV

And then adding to your job’s workspace and attaching it downstream. Downstream jobs will need to have the same echo-append to $BASH_ENV. It’s possible to append to $BASH_ENV directly, but it seems safer and cleaner to separate this logic into a different file.


This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.