Variable as a result of if statement


#1

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.

deploy:
      working_directory: /temp
      docker:
        - image: azuresdk/azure-cli-python:2.0.22
      environment:
        - RG: if [[$CIRCLE_BRANCH=="preproduction"] then Preproduction else Production fi
      steps:
        - 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 webApi.zip
        - run: az webapp deployment source config-zip -g $RG -n facturesAngular$RG --src angular.zip

#2

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.


#3

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


#4

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?


#5

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.


#6

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.


#7

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

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

And then adding conditional_env_vars.sh 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.


#8

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