I've been struggling with this issue for some time now. Environment Variables are generally a good idea to create flexible solutions, but boy, are they tricky when used in a managed solution, deployed by a Power Platform Pipeline. So far the ONLY way that works for me is this:
- Create EV in solution on the DEV environment
- Set "Current Value" to a value appropriate for the DEV environment
- Before EACH (!!!) deployment, REMOVE the value of each EV. (I forgot this today and now I'm in trouble, see below...)
- After deleting the values, deploy the solution to the managed target environment
- During deployment, you'll be asked to specify the value (appropriate to the target environment)
- Complete deployment afterwards
- Go to 2. (Set "Current Value"...) and continue with the next development iteration
This works. But constantly SETTING the values and then REMOVING them again before deploying is cumbersome and dangerous. And wouldn't you know it, today I forgot to remove the values and deployed the solution as is. That worked, but of course the EV values were incorrect. No big deal, I thought, I'll simply re-deploy the solution with the usual step of removing the values. But nope, whenever I try to deploy the solution now, I get this weird error "Cannot insert duplicate key in object 'dbo.EnvironmentVariableValueBase'". I tried different steps, removing the EVs from the solution - deployment fails "Object reference not set to an instance of an object"). Setting the existing EV values on the target environment manually (using the trick with the Default solution, which lets me change EVs outside of the managed solution) then try re-deploying. But that didn't help either.
I'm stuck! It seems having forgot to remove the values killed my chances of re-deploying the solution. Luckily, the target environment is only a TEST environment and scrapping the whole solution will not be a disaster - but soon we will deploy to a production environment and I'm almost certain, that one day I will forget to remove the EV variables again during a rushed deployment and may become stuck again. Scrapping the whole solution won't be possible then. There HAS to be an easier and less dangerous way of using EVs in managed solutions!
A blog post suggested that EVs shouldn't be part of a managed solution at all, instead the should be in their own unmanaged solution and deployed separately to the target environment. I'll experiment with the idea for sure, but I'm also a little doubtful it will work...
Is there a rock-solid Best Practice for this?