I'm facing an issue with dynamically assigning variables in Azure DevOps YAML based on conditions related to the branch name. My goal is to assign specific variables that can later be utilized within tasks. However, I'm encountering problems when attempting to set the AZURE_SUBSCRIPTION variable using conditions in my YAML file.
Here's the relevant part of my YAML:
variables:
BRANCH_NAME: $[replace(variables['Build.SourceBranch'], 'refs/heads/', '')]
${{ if eq(variables['BRANCH_NAME'], 'dev') }}:
TF_ENVIRONMENT: dev
AZURE_SUBSCRIPTION: xxxx
AZURE_SUBSCRIPTION_ID: xxx
${{ elseif eq(variables['BRANCH_NAME'], 'staging') }}:
TF_ENVIRONMENT: stage
AZURE_SUBSCRIPTION: 'test'
AZURE_SUBSCRIPTION_ID: xxxx
${{ elseif eq(variables['BRANCH_NAME'], 'feature/xxx') }}:
TF_ENVIRONMENT: xxx
AZURE_SUBSCRIPTION: xxxx
AZURE_SUBSCRIPTION_ID: xxxx
${{ elseif eq(variables['BRANCH_NAME'], 'master') }}:
TF_ENVIRONMENT: prod
AZURE_SUBSCRIPTION: xxxxx
AZURE_SUBSCRIPTION_ID: xxxxx
steps:
- script:
# ...
- task: AzureCLI@2
inputs:
azureSubscription: $(AZURE_SUBSCRIPTION)
The trick with ${{ if eq(variables['Build.SourceBranchName'], 'dev') }} gets the job done, but it's a no-go for me because it can't handle branches with '/'.
My issue lies in the fact that the AZURE_SUBSCRIPTION variable doesn't seem to be assigned as expected. I suspect there might be an error in my condition logic or how I'm referencing the variable. Could someone please review my YAML and provide insights into why the AZURE_SUBSCRIPTION variable isn't being assigned correctly?
Your string replacement is wrong. Instead of
BRANCH_NAME: $[replace(variables['Build.SourceBranch'], 'refs/heads/', '')]useBRANCH_NAME: ${{ replace(variables['Build.SourceBranch'], 'refs/heads/', '') }}. Notice the replacement of$[]with${{}}.As I mentioned in the comment, you could replace the whole string replacement expression with
BRANCH_NAME: ${{ variables['Build.SourceBranchName'] }}.Build.SourceBranchNamegives you the branch name only. Source here.Edit:
Referencing a variable using runtime expression only works outside complex expressions such as if statement which you are using. To make use of the variables set in the if statement, a compile time expression is needed, such as
${{ variables.AZURE_SUBSCRIPTION }}.Source, Conditional insertion.