Setting environmental variables is handy if we use Azure devops library and there we can have set of variables partitioned by environment. But how do we access those value during development, well its always difficult to debug the solution without right environment variable, to solve that in this article we will see how to access devops env variables in our local solution.
In the below screenshot we’ve created two variable groups dev and prd.
With the following URL we can access the variable group values as a json
https://<tenant-name>.visualstudio.com/<project-name>/_apis/distributedtask/variablegroups?groupId=<variable-group-id>
we can get the variable group id from the URL after opening specific variable group from Azure Devops as shown below,
example: https://fazilsp.visualstudio.com/sppals/_apis/distributedtask/variablegroups?groupId=5
This will return the json value of variables (only if you are already authenticated by browser for your devops). Now we need to find a way how to access this URL from SPFx solution. Well, for that, first and foremost thing is authentication. Here we can use Basic authentication using access token. In the below steps, lets see how to get access token.
Go to user settings -> Personal access tokens
This access token only requires the following rights: Variable Groups (Read) or you can also give full access
After creating personal token we get access token value and now we need to convert this into Basic authorization header value, with the below powershell script
[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("name:accesstoken"))
we successfully generated access token, copy the value inside red box because we need that value for authorization. For quick check lets access variable group values from Postman with the token we just generated.
We successfully retrieved azure devops variable using GET request with the access token we generated. In the upcoming article we will see how to utilize this in our SPFx solution and replace variables with real time data.
Happy coding
Fazil
Leave a comment