A workaround for not being able to access custom variables via stagedependencies if they are set in deployment jobs in Azure DevOps Pipelines

I have blogged in the past ( here and here) about the complexities and possible areas of confusion with different types of Azure DevOps pipeline variables. I have also seen issues raised over how to access custom variables across jobs and stages. Safe to say, this is an area where it is really easy to get it wrong and end up with a null value.

I have recently come across another edge case to add to the list of gotchas.

It seems you cannot use stagedependencies to access a variable declared in a deployment job i.e. when you are using an environment to get approval for a release.

The workaround is to add a job that is dependent on the deployment and set the custom variable within it. This variable can be accessed by a later stage as shown below

 1- stage: S1
 2  jobs:
 3  - deployment: D1
 4    strategy:
 5      runOnce:
 6        deploy:
 7          steps:
 8              - checkout: none
 9              - bash: echo "Can't access the variable if set in here"
10  - job: J1
11    dependsOn:
12      D1
13    steps:
14      - checkout: none
15      - bash: echo "##vso[task.setvariable variable=myvar;isOutput=true]True" 
16        name: BashStep
17
18- stage: S2
19  condition: always()
20
21  dependsOn: 
22   - S1
23  jobs:
24   - job: Use_Variable
25     variables: # add an alias for the var
26       myvar: $[stagedependencies.S1.J1.outputs['BashStep.myvar']]
27        steps:
28          - checkout: none
29          - dash: echo "Script gets run when myvar is true"
30            condition: eq (variables['myvar'],'True')